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>
C# 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
public Dictionary<string, int> AveragePerCategory(List<Entry> entries) {
}
Worked examples
| Call | Result |
|---|---|
AveragePerCategory(new List<Entry> { new Entry("food", 10), new Entry("food", 15) }) | new Dictionary<string, int> { { "food", 13 } } |
AveragePerCategory(new List<Entry> { new Entry("rent", 3000), new Entry("food", 40), new Entry("food", 20) }) | new Dictionary<string, int> { { "rent", 3000 }, { "food", 30 } } |
AveragePerCategory(new List<Entry> { new Entry("x", 0) }) | new Dictionary<string, int> { { "x", 0 } } |
AveragePerCategory(new List<Entry> { }) | new Dictionary<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 C#
public Dictionary<string, int> AveragePerCategory(List<Entry> entries) {
var sums = new Dictionary<string, int>();
var counts = new Dictionary<string, int>();
foreach (var e in entries) {
sums[e.Category] = sums.ContainsKey(e.Category) ? sums[e.Category] + e.Amount : e.Amount;
counts[e.Category] = counts.ContainsKey(e.Category) ? counts[e.Category] + 1 : 1;
}
var result = new Dictionary<string, int>();
foreach (var kv in sums) {
int n = counts[kv.Key];
result[kv.Key] = (kv.Value + n / 2) / n;
}
return result;
}