Start learning free

LESSON 170 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 - Group by Category in Rust

Practice

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

    Shopping Cart V6 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free