Totals per category
A ledger groups every sale under its category so each bucket shows a single sum.
- Add the amounts of every sale under the same category.
- Every category that appears earns an entry in the result.
- The result is one running total per category.
sumPerCategory(sales: list<Sale>) → map<string, int>
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func sumPerCategory(sales []Sale) map[string]int {
}
Worked examples
| Call | Result |
|---|---|
sumPerCategory([]Sale{Sale{Category: "food", Amount: 10}, Sale{Category: "food", Amount: 15}}) | map[string]int{"food": 25} |
sumPerCategory([]Sale{Sale{Category: "a", Amount: 3}, Sale{Category: "b", Amount: 4}, Sale{Category: "a", Amount: 5}}) | map[string]int{"a": 8, "b": 4} |
sumPerCategory([]Sale{Sale{Category: "x", Amount: 1}}) | map[string]int{"x": 1} |
sumPerCategory([]Sale{Sale{Category: "p", Amount: 0}, Sale{Category: "q", Amount: -2}}) | map[string]int{"p": 0, "q": -2} |
Hint
Aggregate into a map keyed by category, adding each amount as you go.
Reference solution in Go
func sumPerCategory(sales []Sale) map[string]int {
result := map[string]int{}
for _, s := range sales {
result[s.Category] += s.Amount
}
return result
}