Skip to content

Instantly share code, notes, and snippets.

@ProProgrammer
Created September 26, 2018 23:42
Show Gist options
  • Save ProProgrammer/6b16240a8da6a6b416c2e824c8c50c27 to your computer and use it in GitHub Desktop.
Save ProProgrammer/6b16240a8da6a6b416c2e824c8c50c27 to your computer and use it in GitHub Desktop.
A Tour of Go: Exercise: Maps Implement WordCount. It should return a map of the counts of each “word” in the string s. The wc.Test function runs a test suite against the provided function and prints success or failure. You might find strings.Fields helpful.
package main
import (
"fmt"
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
outputMap := make(map[string]int)
split_string := strings.Split(s, " ")
for _, item := range split_string {
_, ok := outputMap[item] // check if key exists in outputMap
if ok {
outputMap[item] += 1
} else {
outputMap[item] = 1
}
}
fmt.Println(outputMap)
return outputMap
}
func main() {
wc.Test(WordCount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment