Skip to content

Checkpoint: Report Pending Books in ID Order

The Course
•
30 min study

This checkpoint is a small version of the reading queue's list command. Rows arrive in any order, some of them reuse an ID, and the report must come out sorted by ID with the original record for each ID intact. You will load the rows into a map with a keep-the-first policy, then answer two questions with iterators: which titles are still pending, and how many books are finished.

The interesting part is the duplicates. Each one tries to change something different: one would replace a pending book's title and mark it finished, the other would mark a finished book pending again. A correct program ignores both.

What you will use

  • BTreeMap: one value per key, iterated in ascending key order, so the report is sorted without a separate sort.
  • entry(...).or_insert(...): stores a value only when the key is vacant and leaves an existing value alone.
  • Tuple values: the map can store (title, finished) together, read as .0 and .1.
  • values(), filter, map, collect: a lazy chain that selects pending titles in key order.
  • count: answers "how many finished?" without building a vector.

Plan before you type

  1. Create an empty BTreeMap and loop over the rows, destructuring each one as (id, title, done).
  2. Insert with entry(id).or_insert((title, done)) so a repeated ID changes nothing.
  3. Assert that IDs 5 and 7 still hold their first records.
  4. Build the pending list from books.values(), keeping records whose .1 is false and selecting .0.
  5. Count finished records with a second, fresh iterator.
  6. Print Pending: with the titles joined by commas, then Finished: with the count.
Prove it can fail

Once your solution passes, replace the entry line with books.insert(id, (title, done)); and run again. Your assertions should fail. Then remove the assertions and look at the output: the finished count is still 1, because one duplicate flipped a book to finished and the other flipped a book back. A check on the count alone would have missed the bug, which is why the assertions inspect the stored records. Restore entry when you are done.

Mistakes worth checking for

  • Titles print in input order (Rust before Traits): the records went into a Vec instead of a map, or the report iterates over rows instead of books.
  • Slices again appears as pending: the code uses insert, so the last row for ID 5 won.
  • Only Slices is listed as pending: the filter tests book.1, which keeps finished books; pending means !book.1.
  • use of moved value on the second query: you stored one iterator in a variable and consumed it twice; start a new books.values() for each question.

Build it

Exercise

Your turn

Load the supplied rows into a BTreeMap keyed by ID, keeping the first record for each ID. Assert that ID 7 is still ("Rust", false) and ID 5 is still ("Slices", true). Then print the pending titles in ID order and the number of finished books. The expected output is:

Text
Pending: Traits, Rust
Finished: 1
Your working space Rust
fn main() {
    let rows = [(7, "Rust", false), (3, "Traits", false), (5, "Slices", true),
                (7, "Replacement", true), (5, "Slices again", false)];
    // Insert each record once, then query the map.
    println!("Input rows: {}", rows.len());
}
Hint 1: the idea

The map can store a tuple holding the title and status. Order comes from the keys, and the first-value rule comes from how you insert.

Hint 2: a first step

Use books.entry(id).or_insert((title, done)); inside the loop. or_insert returns a reference you do not need here, so the statement can end with a semicolon.

Worked solution
Run the solution Rust
use std::collections::BTreeMap;

fn main() {
    let rows = [(7, "Rust", false), (3, "Traits", false), (5, "Slices", true),
                (7, "Replacement", true), (5, "Slices again", false)];
    let mut books = BTreeMap::new();
    for (id, title, done) in rows {
        books.entry(id).or_insert((title, done));
    }
    assert_eq!(books.get(&7), Some(&("Rust", false)));
    assert_eq!(books.get(&5), Some(&("Slices", true)));

    let pending: Vec<&str> = books.values()
        .filter(|book| !book.1)
        .map(|book| book.0)
        .collect();
    println!("Pending: {}", pending.join(", "));
    println!("Finished: {}", books.values().filter(|book| book.1).count());
}
Text
Pending: Traits, Rust
Finished: 1

values() visits records in key order, 3, 5, 7, and filter keeps that order, so Traits comes before Rust even though Rust arrived first. The two assertions are what protect the duplicate policy; the printed lines alone would not catch every wrong version. On Day 5 you will replace these hard-coded rows with commands parsed from text.

Was this article helpful?

Your response is saved on this device.