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 = arrayOf("Apple", "Bread", "Shirt", "Banana", "Pants")
val prices = intArrayOf(2, 3, 25, 1, 40)
val categories = arrayOf("Food", "Food", "Clothes", "Food", "Clothes")
Build:
Clothes: $65 Food: $6
Rules:
- Build a mutable map
totalsthat 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 (soClothescomes beforeFood). - Join the lines with a newline
"\n"into one stringresult, then print it withprintln(result).
Use
totals.getOrDefault(cat, 0) + prices[i] to accumulate without checking for missing keys.
Use
totals.keys.sorted() to get the keys in alphabetical order.
val items = arrayOf("Apple", "Bread", "Shirt", "Banana", "Pants")
val prices = intArrayOf(2, 3, 25, 1, 40)
val categories = arrayOf("Food", "Food", "Clothes", "Food", "Clothes")
val totals = mutableMapOf<String, Int>()
for (i in items.indices) {
val cat = categories[i]
totals[cat] = totals.getOrDefault(cat, 0) + prices[i]
}
val lines = mutableListOf<String>()
val keys = totals.keys.sorted()
for (cat in keys) {
lines.add(cat + ": $" + totals[cat])
}
val result = lines.joinToString("\n")
println(result)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
