Counting with Maps
"How many times does X appear?" is one of the most common questions in puzzles. The answer is nearly always a map[T]int. Since a missing key reads as 0, you can increment it straight away:
counts := make(map[string]int)
for _, word := range words {
counts[word]++
}
One pass over the data, and every increment takes (on average) constant time. Compare that with recounting every word using a loop inside a loop: for 10,000 words, that's 100 million steps.
Map order is random
Iterating with for k, v := range counts has no guaranteed order, and it can change from one run to the next. Puzzles almost always want one definite answer, so when order matters, collect the keys into a slice and sort it:
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
slices.Sort(keys) // alphabetical
Sorting by your own rule
slices.SortFunc takes a comparison function that returns a negative number, zero or a positive number. cmp.Compare produces that number for any two comparable values. For "highest count first, then alphabetical on a tie":
slices.SortFunc(keys, func(a, b string) int {
if c := cmp.Compare(counts[b], counts[a]); c != 0 {
return c // b goes first when its count is bigger
}
return cmp.Compare(a, b) // a tie: alphabetical
})
Notice the order counts[b], counts[a]: swapping the arguments flips the order to largest first.
Task
A book club is voting on next month's read. Every line of the input is one vote holding a book title.
- Complete
tally(lines []string) map[string]int. Trim every line withstrings.TrimSpace, skip blank lines, and count how often each title appears. Upper and lower case count as different. For input with no votes, return an empty map (notnil). - Complete
topN(counts map[string]int, n int) []string: at mostntitles, most votes first, and titles with the same number of votes in alphabetical order (cmp.Compareon strings). If there are fewer thanntitles, return them all.