Start learning free

LESSON 194 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Scala: Group Totals by Category

Practice Read the full explanation

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

You start with:

        val items = Array("Apple", "Bread", "Shirt", "Banana", "Pants")
        val prices = Array(2, 3, 25, 1, 40)
        val categories = Array("Food", "Food", "Clothes", "Food", "Clothes")

Build:

Clothes: $65
Food: $6

Rules:

  • Build a mutable map 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.getOrElse(cat, 0) + prices(i) to accumulate without checking for missing keys.

Use totals.keys.toSeq.sorted to get the keys in alphabetical order.

        val items = Array("Apple", "Bread", "Shirt", "Banana", "Pants")
        val prices = Array(2, 3, 25, 1, 40)
        val categories = Array("Food", "Food", "Clothes", "Food", "Clothes")

        val totals = scala.collection.mutable.Map[String, Int]()
        for (i <- items.indices) {
            val cat = categories(i)
            totals(cat) = totals.getOrElse(cat, 0) + prices(i)
        }
        val lines = scala.collection.mutable.ArrayBuffer[String]()
        val keys = totals.keys.toSeq.sorted
        for (cat <- keys) {
            lines += cat + ": $" + totals(cat)
        }
        val result = lines.mkString("\n")
        println(result)

STEP 1 OF 10
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Scala, explained

    Problem overview

    This version groups items by category. Three arrays run in parallel: items, prices and categories. The program adds up the prices for each category and prints one row per category, sorted alphabetically by the category's name, in the format Category: $total.

    For items Apple, Bread, Shirt, Banana and Pants, prices 2, 3, 25, 1 and 40, and categories Food, Food, Clothes, Food and Clothes, the output is:

    Clothes: $65
    Food: $6

    Clothes is 25 + 40 and Food is 2 + 3 + 1. Clothes comes first, because it comes first in alphabetical order, not because it appeared first in the data.

    Approach: accumulate in a map, then sort the keys

    The number of categories is not known in advance, so there are no fixed counters to name. A mutable map from category to running total handles any number of them. Each item adds its price to its category's entry. The first item of a category finds no entry yet, so the sum starts from 0: getOrElse(cat, 0) supplies that starting point.

    A map does not promise any order, so the rows cannot just follow the map. The keys are sorted into a sequence first, and the rows are built in that order. That gives the same output no matter in which order the items appeared.

    Step by step

    1. Create totals, an empty scala.collection.mutable.Map[String, Int](). The type says that keys are text and values are integers.
    2. Loop over the positions with for (i <- items.indices). One index reaches the same item in every array.
    3. Read the category of the current item into cat with categories(i).
    4. Update the total. Assign totals(cat) the old total, from getOrElse(cat, 0), plus prices(i).
    5. After the loop, create lines, an empty ArrayBuffer[String] for the rows.
    6. Sort the keys. totals.keys.toSeq.sorted turns the keys into a sequence and puts them in alphabetical order.
    7. Loop over the sorted keys with for (cat <- keys).
    8. Add a row for each category with +=: the name, a colon, $ and the total.
    9. Join the rows into result with a newline between each two, using mkString.
    10. Print result.

    The solution in Scala

            val items = Array("Apple", "Bread", "Shirt", "Banana", "Pants")
            val prices = Array(2, 3, 25, 1, 40)
            val categories = Array("Food", "Food", "Clothes", "Food", "Clothes")
    
            val totals = scala.collection.mutable.Map[String, Int]()
            for (i <- items.indices) {
                val cat = categories(i)
                totals(cat) = totals.getOrElse(cat, 0) + prices(i)
            }
            val lines = scala.collection.mutable.ArrayBuffer[String]()
            val keys = totals.keys.toSeq.sorted
            for (cat <- keys) {
                lines += cat + ": $" + totals(cat)
            }
            val result = lines.mkString("\n")
            println(result)

    Some language details:

    • totals(cat) = ... is Scala's way to put a value in a mutable map: writing to totals(cat) calls the map's update method, and it adds the key if it is new. Reading totals(cat) on a missing key is the dangerous operation, which throws NoSuchElementException. Writing is always safe.
    • Why getOrElse in the update. The shorter totals(cat) += prices(i) reads the old value first, so it throws on the first item of each category. A missing key has no automatic zero in Scala, so the program supplies it.
    • keys.toSeq.sorted. sorted needs an ordering for the elements, and strings have a natural one, character by character. The result is a new sequence, and the map is not changed.
    • lines += ... on an ArrayBuffer appends the element. Because lines is a val, the name never changes, only the buffer's contents do.

    Complexity

    With n items and k distinct categories, the first loop makes one pass over the items, and each map update takes constant time on average, so it costs O(n). Sorting the keys costs O(k log k), and building the rows is O(k). Since k is at most n, the whole program is O(n log n) in the worst case and usually much closer to O(n), because there are normally few categories. The map and the buffer use O(k) extra space.

    Edge cases and common mistakes

    • Capital letters sort first. The ordering compares characters by code, so every uppercase letter comes before every lowercase one. For categories home and Toys the output is Toys: $50 and then home: $30. All the lesson's categories start with a capital letter, so this matters only if the data does not.
    • Reading before writing. Using totals(cat) without getOrElse crashes at the first item of each category with key not found.
    • Relying on the map's own order. A mutable map is a hash map, and its iteration order is not alphabetical and should not be depended on. That is why the keys are sorted.
    • Mixing up the two loops. The first loop is over item positions, and the second over the distinct categories. A category with three items gets one row, not three.
    • Empty input. With empty arrays the map is empty, there are no rows, and result is the empty string.

    Testing

    A cart of two items, Lamp (30) in home and Rug (50) in Toys, prints Toys: $50 and home: $30, as described above. Change the arrays in the editor above, for instance so every item has the same category, and check that you get one row with the sum of all the prices.

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