Problem overview
Version 6 groups the cart by category. Three parallel vectors describe five items: items, prices and categories. The program must add up the prices per category and print one line per category, sorted alphabetically by the category name:
Clothes: $65
Food: $6
Shirt (25) and Pants (40) are Clothes, which makes 65. Apple (2), Bread (3) and Banana (1) are Food, which makes 6. The starter already declares an empty map, totals.
Approach: accumulate in a map, then sort the keys
The task has two phases. First, a loop over the positions adds each price to its category's running total in a HashMap. A category's first item finds no total yet, so the sum has to start from 0.
Second, the rows are produced. A HashMap gives no promise about the order of its entries, so iterating it directly could print Food before Clothes. The fix is to copy the keys into a vector, sort the vector and look each key up in the map in that order.
Step by step
- Loop over the positions with
for i in 0..items.len(), since the three vectors line up by index. - Read the category of the current item into
cat. - Add the price to the category's total with
*totals.entry(cat).or_insert(0) += prices[i].entry(cat)locates the slot for that key,or_insert(0)puts a 0 there if the slot is empty and returns a mutable reference to the number, and the*dereferences it so that+=changes the stored value. - Create
linesas an empty vector withlet mut. - Collect the keys into
keys, aVec<&str>, withtotals.keys().copied().collect(). It ismutbecause it is about to be sorted. - Sort
keyswithkeys.sort(), which rearranges the vector in place. - Loop over the sorted keys with
for cat in keys. - Push each row with
format!("{}: ${}", cat, totals[cat]). - Join the rows with
lines.join("\n")intoresult. - Print
resultwithprintln!.
The solution in Rust
let items = vec!["Apple", "Bread", "Shirt", "Banana", "Pants"];
let prices = vec![2, 3, 25, 1, 40];
let categories = vec!["Food", "Food", "Clothes", "Food", "Clothes"];
let mut totals = HashMap::new();
for i in 0..items.len() {
let cat = categories[i];
*totals.entry(cat).or_insert(0) += prices[i];
}
let mut lines = Vec::new();
let mut keys: Vec<&str> = totals.keys().copied().collect();
keys.sort();
for cat in keys {
lines.push(format!("{}: ${}", cat, totals[cat]));
}
let result = lines.join("\n");
println!("{}", result);
Rust details worth knowing:
- Type inference for the map.
HashMap::new()names no types. The compiler infersHashMap<&str, i32>from the calls that use it: the key fromentry(cat)and the value from addingprices[i]. - The
entryAPI. It avoids the two-step "look up, then insert if missing". A single expression handles both the first and later items of a category. - Why
copied().keys()yields&&str, references to the stored keys.copied()turns each into a plain&str, matching the declaredVec<&str>. - Strings sort lexicographically by their bytes, so uppercase letters come before lowercase ones.
- Indexing a map.
totals[cat]returns the value and panics if the key is missing. That is safe here because every key came from the map itself. for cat in keysconsumes the vector. That is fine: it is not used afterwards.
Complexity
Time: O(n + k log k), where n is the number of items and k the number of distinct categories. The first loop is one map update per item, and sorting the keys costs k log k.
Space: O(n) in the worst case, for the map, the key vector and the rows. When every item has its own category, k equals n.
Tracing the map
Following the first loop item by item shows each category's total as it builds up:
Apple (2): Food total is now 2
Bread (3): Food total is now 5
Shirt (25): Clothes total is now 25
Banana (1): Food total is now 6
Pants (40): Clothes total is now 65
Apple is the first Food item, so or_insert(0) creates its slot and the price is added to that 0. Bread and Banana find the slot and add to it. Once the loop ends, the sorted keys are ["Clothes", "Food"], and the second loop reads each total from the map in that order.
Why sort the keys, not the map
A HashMap has no sorted order to sort. Its entries sit wherever their hashes put them, which is what makes lookup fast. When a program needs ordered output it moves the keys into a vector, which does have an order, sorts that and reads the values back by key. Another map type, BTreeMap, keeps its keys sorted by itself; this lesson uses HashMap to practise the collect-then-sort pattern.
Edge cases and common mistakes
- Skipping the sort. Rows then come out in whatever order the map yields, which can differ between runs.
- Case in category names. With categories
food,FoodandZoothe output isFood: $2,Zoo: $3,food: $1. They are different keys, and uppercase sorts first. - Forgetting the
*.totals.entry(cat).or_insert(0) += prices[i]does not compile, because the left side is a reference, not a number. - Vectors of different lengths. With two items and one category, indexing
categories[1]panics withindex out of bounds: the len is 1 but the index is 1. - No items. An empty cart gives an empty map, no rows and an empty
result, soprintln!prints just a blank line.
Testing
- The five items above give
Clothes: $65andFood: $6. - Pen (4, Office), Apple (2, Food) and Shirt (25, Clothes) give
Clothes: $25,Food: $2andOffice: $4, in that order. - Three items in
food,FoodandZoowith prices 1, 2 and 3 give the three lines listed above.
