Skip to content

Instantly share code, notes, and snippets.

@tommylees112
Created April 19, 2021 17:14
Show Gist options
  • Save tommylees112/a8d20efefb4145ea1770e5b84b342b8b to your computer and use it in GitHub Desktop.
Save tommylees112/a8d20efefb4145ea1770e5b84b342b8b to your computer and use it in GitHub Desktop.
Maps exercise from ["A Tour of Go"](https://tour.golang.org/welcome/1)
package main
import (
"fmt"
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
// create a slice of strings with each of the inputs
var fields []string = strings.Fields(s)
// initialise the map variable for storing the results
duplicate_frequency := make(map[string]int)
// iterate over each value in the field (ignore the index)
for _, item := range fields {
// does the key exist?
_, exist := duplicate_frequency[item]
if exist {
// increment counter
duplicate_frequency[item] += 1
} else {
// start counter
duplicate_frequency[item] = 1
}
}
return duplicate_frequency
}
func main() {
wc.Test(WordCount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment