How many of each
A survey tallies how often each answer was given.
- Count how many times each distinct string appears.
- Every distinct value that appears earns an entry in the result.
groupSizes(values: list<string>) → 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> groupSizes(std::vector<std::string> values) {
}
Worked examples
| Call | Result |
|---|---|
groupSizes(std::vector<std::string>{std::string("a"), std::string("b"), std::string("a")}) | std::map<std::string, int>{{std::string("a"), 2}, {std::string("b"), 1}} |
groupSizes(std::vector<std::string>{std::string("x")}) | std::map<std::string, int>{{std::string("x"), 1}} |
groupSizes(std::vector<std::string>{std::string("p"), std::string("p"), std::string("p")}) | std::map<std::string, int>{{std::string("p"), 3}} |
groupSizes(std::vector<std::string>{std::string("a"), std::string("b"), std::string("c")}) | std::map<std::string, int>{{std::string("a"), 1}, {std::string("b"), 1}, {std::string("c"), 1}} |
Hint
Add one to the map entry for each value you meet.
Reference solution in C++
std::map<std::string, int> groupSizes(std::vector<std::string> values) {
std::map<string, int> result;
for (const auto& v : values) result[v]++;
return result;
}