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
std::map<std::string, int> averagePerCategory(std::vector<Entry> entries) {
}
Worked examples
| Call | Result |
|---|---|
averagePerCategory(std::vector<Entry>{Entry{std::string("food"), 10}, Entry{std::string("food"), 15}}) | std::map<std::string, int>{{std::string("food"), 13}} |
averagePerCategory(std::vector<Entry>{Entry{std::string("rent"), 3000}, Entry{std::string("food"), 40}, Entry{std::string("food"), 20}}) | std::map<std::string, int>{{std::string("rent"), 3000}, {std::string("food"), 30}} |
averagePerCategory(std::vector<Entry>{Entry{std::string("x"), 0}}) | std::map<std::string, int>{{std::string("x"), 0}} |
averagePerCategory(std::vector<Entry>{}) | std::map<std::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++
std::map<std::string, int> averagePerCategory(std::vector<Entry> entries) {
std::map<string, int> sums, counts;
for (const auto& e : entries) {
sums[e.category] += e.amount;
counts[e.category]++;
}
std::map<string, int> result;
for (const auto& kv : sums) {
int n = counts[kv.first];
result[kv.first] = (kv.second + n / 2) / n;
}
return result;
}