Start learning free

LESSON 197 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Rust: Group Totals by Category

Practice Read the full explanation

Use a HashMap to accumulate totals per category while looping over parallel vectors, then list the categories sorted by name.

You start with:

        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();

Build:

Clothes: $65
Food: $6

Rules:

  • Build a HashMap totals that maps each category to the sum of the prices of its items.
  • Loop with an index. For each item, add its price to the total of categories[i]; a category you have not seen yet counts as 0.
  • Make one line per category, in the format "Category: $total", sorted alphabetically by category name (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with println!("{}", result).

Use *totals.entry(cat).or_insert(0) += prices[i];: entry starts a missing category at 0.

Collect the keys into a vector and call keys.sort() before building the lines.

        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);

STEP 1 OF 10
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Rust, explained

    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

    1. Loop over the positions with for i in 0..items.len(), since the three vectors line up by index.
    2. Read the category of the current item into cat.
    3. 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.
    4. Create lines as an empty vector with let mut.
    5. Collect the keys into keys, a Vec<&str>, with totals.keys().copied().collect(). It is mut because it is about to be sorted.
    6. Sort keys with keys.sort(), which rearranges the vector in place.
    7. Loop over the sorted keys with for cat in keys.
    8. Push each row with format!("{}: ${}", cat, totals[cat]).
    9. Join the rows with lines.join("\n") into result.
    10. Print result with println!.

    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 infers HashMap<&str, i32> from the calls that use it: the key from entry(cat) and the value from adding prices[i].
    • The entry API. 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 declared Vec<&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 keys consumes 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, Food and Zoo the output is Food: $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 with index 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, so println! prints just a blank line.

    Testing

    • The five items above give Clothes: $65 and Food: $6.
    • Pen (4, Office), Apple (2, Food) and Shirt (25, Clothes) give Clothes: $25, Food: $2 and Office: $4, in that order.
    • Three items in food, Food and Zoo with prices 1, 2 and 3 give the three lines listed above.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free