Problem Solving with Go course

Maps and SetsCounting with Maps

Problem Solving with Go

Display

Theme

Maps and Sets · Test exercise

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.

  1. Complete tally(lines []string) map[string]int. Trim every line with strings.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 (not nil).
  2. Complete topN(counts map[string]int, n int) []string: at most n titles, most votes first, and titles with the same number of votes in alphabetical order (cmp.Compare on strings). If there are fewer than n titles, return them all.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// tally counts how many times each non-blank line appears. Lines are trimmed first.
func tally(lines []string) map[string]int {
	// TODO
	return nil
}

// topN returns up to n keys with the highest counts: highest count first,
// equal counts in alphabetical order.
func topN(counts map[string]int, n int) []string {
	// TODO: collect the keys into a slice, sort it with slices.SortFunc, keep n
	return nil
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	counts := tally(strings.Split(string(data), "\n"))
	for _, title := range topN(counts, 3) {
		fmt.Println(counts[title], title)
	}
}
Go runtime not loaded yet

10 lines · 163 B of the 1 MB limit. Submit always uses the lesson's own input.