Drill

ProblemsC# › reporting

Average spend per category

mediumreportingHash mapsArraysC#

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

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.

Solve it in Python →

Where you start

public Dictionary<string, int> AveragePerCategory(List<Entry> entries) {
    
}

Worked examples

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

The same problem in another language

More reporting problems in C#