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
public Dictionary<string, int> GroupSizes(List<string> values) {
}
Worked examples
| Call | Result |
|---|---|
GroupSizes(new List<string> { "a", "b", "a" }) | new Dictionary<string, int> { { "a", 2 }, { "b", 1 } } |
GroupSizes(new List<string> { "x" }) | new Dictionary<string, int> { { "x", 1 } } |
GroupSizes(new List<string> { "p", "p", "p" }) | new Dictionary<string, int> { { "p", 3 } } |
GroupSizes(new List<string> { "a", "b", "c" }) | new Dictionary<string, int> { { "a", 1 }, { "b", 1 }, { "c", 1 } } |
Hint
Add one to the map entry for each value you meet.
Reference solution in C#
public Dictionary<string, int> GroupSizes(List<string> values) {
var result = new Dictionary<string, int>();
foreach (var v in values) {
if (result.ContainsKey(v)) result[v] += 1;
else result[v] = 1;
}
return result;
}