Bitpath

Boss lesson · Unit 04

A word counter

Split a text into words, count them in a map, sort the keys and report the most common.

13 exercisesabout 3 min

What you practise

  • Text split into words, counted in a map, sorted and reported: most common first

Try a question from this lesson

Pick one

strings.Fields cuts a text at its spaces and hands back a slice of the words. What does this print?

Go
text := "the cat saw the dog"
words := strings.Fields(text)
fmt.Println(len(words), words[1])

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The plan

The job: read a text and report how often each word appears, most common first.

The plan has three steps, and you know a tool for each. Split the text into words with strings.Fields. Count the words in a map from string to int: counts[w]++. Then put the keys in a fixed order and print the report.

Go
text := "to be or not to be"
counts := make(map[string]int)
for _, w := range strings.Fields(text) {
  counts[w]++
}
fmt.Println(counts["to"], counts["or"])
// 2 1

Concept

A fixed order: sorted keys

A map has no order, so a report straight from range would change from run to run.

The cure: collect the keys into a slice, then sort the slice. sort.Strings puts a slice of strings into alphabetical order. A range with one variable gives just the keys.

Go
counts := map[string]int{"b": 2, "a": 1}
var keys []string
for k := range counts {
  keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys) // [a b]

Concept

Most common first

To print every word, most common first, repeat one move until the map is empty: find the best word, print it, then delete it from the map so that the next round finds the runner-up.

Here counts is the map and keys holds its sorted keys. A deleted key reads as 0, so it can never win again.

Go
for len(counts) > 0 {
  best := keys[0]
  for _, k := range keys {
    if counts[k] > counts[best] {
      best = k
    }
  }
  fmt.Println(best, counts[best])
  delete(counts, best)
}

9 more exercises in the app

  • 1× order the lines
  • 2× multiple choice
  • 1× fill the blanks
  • 4× type the answer
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy