Average spend per category
A budgeting view shows what a typical transaction looks like in each category.
- Amounts are never negative.
- The average is a whole number, rounded half up: 12.5 becomes 13.
- A category with no entries never appears.
averagePerCategory(entries: list<Entry>) → 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 averagePerCategory(entries []Entry) map[string]int {
}
Worked examples
| Call | Result |
|---|---|
averagePerCategory([]Entry{Entry{Category: "food", Amount: 10}, Entry{Category: "food", Amount: 15}}) | map[string]int{"food": 13} |
averagePerCategory([]Entry{Entry{Category: "rent", Amount: 3000}, Entry{Category: "food", Amount: 40}, Entry{Category: "food", Amount: 20}}) | map[string]int{"rent": 3000, "food": 30} |
averagePerCategory([]Entry{Entry{Category: "x", Amount: 0}}) | map[string]int{"x": 0} |
averagePerCategory([]Entry{}) | map[string]int{} |
Hint
Collect sums and counts side by side, then divide once at the end. (sum + count / 2) / count rounds half up in integers.
Reference solution in Go
func averagePerCategory(entries []Entry) map[string]int {
sums := map[string]int{}
counts := map[string]int{}
for _, e := range entries {
sums[e.Category] += e.Amount
counts[e.Category]++
}
result := map[string]int{}
for k, s := range sums {
n := counts[k]
result[k] = (s + n/2) / n
}
return result
}