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>
Go 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
func groupSizes(values []string) map[string]int {
}
Worked examples
| Call | Result |
|---|---|
groupSizes([]string{"a", "b", "a"}) | map[string]int{"a": 2, "b": 1} |
groupSizes([]string{"x"}) | map[string]int{"x": 1} |
groupSizes([]string{"p", "p", "p"}) | map[string]int{"p": 3} |
groupSizes([]string{"a", "b", "c"}) | map[string]int{"a": 1, "b": 1, "c": 1} |
Hint
Add one to the map entry for each value you meet.
Reference solution in Go
func groupSizes(values []string) map[string]int {
result := map[string]int{}
for _, v := range values {
result[v]++
}
return result
}