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.0and.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
- Create an empty
BTreeMapand loop over the rows, destructuring each one as(id, title, done). - Insert with
entry(id).or_insert((title, done))so a repeated ID changes nothing. - Assert that IDs 5 and 7 still hold their first records.
- Build the pending list from
books.values(), keeping records whose.1isfalseand selecting.0. - Count finished records with a second, fresh iterator.
- Print
Pending:with the titles joined by commas, thenFinished: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 (
RustbeforeTraits): the records went into aVecinstead of a map, or the report iterates overrowsinstead ofbooks. Slices againappears as pending: the code usesinsert, so the last row for ID 5 won.- Only
Slicesis listed as pending: the filter testsbook.1, which keeps finished books; pending means!book.1. use of moved valueon the second query: you stored one iterator in a variable and consumed it twice; start a newbooks.values()for each question.
Build it
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:
Pending: Traits, Rust
Finished: 1fn 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
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());
}Pending: Traits, Rust
Finished: 1values() 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.
Completion is saved in this browser only. It does not measure mastery.