Drill

ProblemsGo › reporting

Average spend per category

mediumreportingHash mapsArraysGo

A budgeting view shows what a typical transaction looks like in each category.

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.

Solve it in Python →

Where you start

func averagePerCategory(entries []Entry) map[string]int {
	
}

Worked examples

CallResult
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
}

The same problem in another language

More reporting problems in Go