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>
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> SumPerCategory(List<Sale> sales) {
}
Worked examples
| Call | Result |
|---|---|
SumPerCategory(new List<Sale> { new Sale("food", 10), new Sale("food", 15) }) | new Dictionary<string, int> { { "food", 25 } } |
SumPerCategory(new List<Sale> { new Sale("a", 3), new Sale("b", 4), new Sale("a", 5) }) | new Dictionary<string, int> { { "a", 8 }, { "b", 4 } } |
SumPerCategory(new List<Sale> { new Sale("x", 1) }) | new Dictionary<string, int> { { "x", 1 } } |
SumPerCategory(new List<Sale> { new Sale("p", 0), new Sale("q", -2) }) | new Dictionary<string, int> { { "p", 0 }, { "q", -2 } } |
Hint
Aggregate into a map keyed by category, adding each amount as you go.
Reference solution in C#
public Dictionary<string, int> SumPerCategory(List<Sale> sales) {
var result = new Dictionary<string, int>();
foreach (var s in sales) {
if (result.ContainsKey(s.Category)) result[s.Category] += s.Amount;
else result[s.Category] = s.Amount;
}
return result;
}