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
- Create
totals, an emptyscala.collection.mutable.Map[String, Int](). The type says that keys are text and values are integers. - Loop over the positions with
for (i <- items.indices). One index reaches the same item in every array. - Read the category of the current item into
catwithcategories(i). - Update the total. Assign
totals(cat)the old total, fromgetOrElse(cat, 0), plusprices(i). - After the loop, create
lines, an emptyArrayBuffer[String]for the rows. - Sort the keys.
totals.keys.toSeq.sortedturns the keys into a sequence and puts them in alphabetical order. - Loop over the sorted keys with
for (cat <- keys). - Add a row for each category with
+=: the name, a colon,$and the total. - Join the rows into
resultwith a newline between each two, usingmkString. - 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 tototals(cat)calls the map'supdatemethod, and it adds the key if it is new. Readingtotals(cat)on a missing key is the dangerous operation, which throwsNoSuchElementException. Writing is always safe.- Why
getOrElsein the update. The shortertotals(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.sortedneeds 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 anArrayBufferappends the element. Becauselinesis aval, 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
homeandToysthe output isToys: $50and thenhome: $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)withoutgetOrElsecrashes at the first item of each category withkey 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
resultis 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.
