Exercise 12 / 24: Print Batches

// Iterators of Code 2026 — Day 12: Print Batches
// Challenge: Group print jobs into batches of at most three, preserving order.
// Keep the final partial batch, but never emit an empty batch. Refactor the loop.

fn print_batches<'a>(jobs: &[&'a str]) -> Vec<Vec<&'a str>> {
    let mut batches = Vec::new();
    let mut batch = Vec::new();

    for job in jobs {
        batch.push(*job);
        if batch.len() == 3 {
            batches.push(batch);
            batch = Vec::new();
        }
    }
    if !batch.is_empty() {
        batches.push(batch);
    }

    batches
}

fn main() {
    assert_eq!(
        print_batches(&[
            "invoice", "label", "map", "receipt", "menu", "form", "ticket"
        ]),
        vec![
            vec!["invoice", "label", "map"],
            vec!["receipt", "menu", "form"],
            vec!["ticket"]
        ]
    );
    assert_eq!(print_batches(&["a", "b", "c"]), vec![vec!["a", "b", "c"]]);
    assert_eq!(print_batches(&["a", "b"]), vec![vec!["a", "b"]]);
    assert_eq!(print_batches(&["a"]), vec![vec!["a"]]);
    assert!(print_batches(&[]).is_empty());
}

Your solution

Standalone .rs / std only. Stored, not executed.

60 characters max. Not a login.

File overrides pasted code.

Maximum solution size: 64 KiB.

Editing access uses this browser's cookie. Clearing cookies loses access.