Created
April 19, 2021 17:14
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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