Counting with a map is the most common map pattern.
What to build
A program that counts votes for each candidate.
Requirements
- Read n, then n names (one word each).
- Print one line
NAME: COUNTper candidate, sorted alphabetically by name.
Input
Line 1: n. Then n names.
Output
One line per candidate.
Constraints
1 ≤ n ≤ 100; names have 1 to 15 letters; names are case sensitive.
Example
Input:
5
Ada Bob Ada Cy Bob
Output:
Ada: 2
Bob: 2
Cy: 1
Why it works
The map adds one to the counter of each name. Because map order is random, the keys are sorted before printing so that the output is always the same.
Examples
Example 1 · Input
5 Ada Bob Ada Cy Bob
Expected output
Ada: 2 Bob: 2 Cy: 1
Example 2 · Input
3 Zed Zed Zed
Expected output
Zed: 3
Hints
Hint 1
Use a map[string]int and count[name]++ for every vote.
Hint 2
Collect the keys, sort them with sort.Strings and print in that order.
Solution
Show one correct solution (try it yourself first)
package main
import (
"fmt"
"sort"
)
func main() {
var n int
fmt.Scan(&n)
count := make(map[string]int)
for i := 0; i < n; i++ {
var name string
fmt.Scan(&name)
count[name]++
}
names := []string{}
for k := range count {
names = append(names, k)
}
sort.Strings(names)
for _, k := range names {
fmt.Printf("%s: %d\n", k, count[k])
}
}