DEV Community

Robin Moffatt
Robin Moffatt

Posted on • Originally published at rmoff.net on

Learning Golang (some rough notes) - S01E03 - Maps

👉 A Tour of Go : Exercise - Maps

Implement WordCount

This is probably bread-and-butter for any seasoned programmer, but I enjoyed the simple process and satisfaction of breaking the problem down into steps to solve using what the tutorial had just covered. Sketching out the logic in pseudo-code first, I figured that I wanted to do this:

  • For each word in the phrase:

    • Check if the word exists in the map already
      • Create it if it doesn’t
    • Add one to the map value

Using Printf it was useful to check on how it was executing.

func WordCount(s string) map[string]int {
    w := make(map[string]int)

    for i, v := range strings.Fields(s) {
        fmt.Printf("Index: %d value %v\n",i, v)
        if _, o := w[v]; o == true {
            fmt.Printf("\tExisting map found for %v with value %d\n",v,w[v])
            w[v] = w[v] + 1
        } else {
            fmt.Printf("\tCreating new map for %v with value 1\n",v)
            w[v] = 1
        }
    }

    return w
}
Enter fullscreen mode Exit fullscreen mode

I liked that the tutorial uses tests to check what you’ve done, and shows the expected output:

PASS
 f("I am learning Go!") = 
  map[string]int{"Go!":1, "I":1, "am":1, "learning":1}
PASS
 f("The quick brown fox jumped over the lazy dog.") = 
  map[string]int{"The":1, "brown":1, "dog.":1, "fox":1, "jumped":1, "lazy":1, "over":1, "quick":1, "the":1}
PASS
 f("I ate a donut. Then I ate another donut.") = 
  map[string]int{"I":2, "Then":1, "a":1, "another":1, "ate":2, "donut.":2}
PASS
 f("A man a plan a canal panama.") = 
  map[string]int{"A":1, "a":2, "canal":1, "man":1, "panama.":1, "plan":1}
Enter fullscreen mode Exit fullscreen mode

Looking at the pseudo-code and what Golang will handle for you automagically it can be reduced to this:

  • For each word in the phrase:

    • Check if the word exists in the map already
      • Create it if it doesn’t
    • Add one to the map value (implicitly create the map entry if it doesn’t already exist)
func WordCount(s string) map[string]int {
    w := make(map[string]int)

    for _, v := range strings.Fields(s) {
        w[v] = w[v] + 1
    }

    return w
}
Enter fullscreen mode Exit fullscreen mode

Note: the underscore character, representing a required variable that you’re not going to use, is pretty useful.

Top comments (0)