3
\$\begingroup\$

My quick searching did not reveal anyone sharing their solution to this exercise, so am not sure if there are other (and better) approaches to mine:

package main
import (
 "code.google.com/p/go-tour/wc"
 "strings"
)
func WordCount(s string) map[string]int {
 foo := strings.Fields(s)
 m := make(map[string]int)
 for i := 0; i < len(foo); i++ {
 v, ok := m[foo[i]]
 if ok {
 m[foo[i]] = v + 1
 }
 m[foo[i]] = v + 1
 }
 return m
}
func main() {
 wc.Test(WordCount)
}
asked Mar 27, 2013 at 14:29
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

You can be more concise and readable using range and the fact that the default value of the int is 0 :

func WordCount(s string) map[string]int {
 m := make(map[string]int)
 for _, w := range(strings.Fields(s)) {
 m[w]++
 }
 return m
}
answered Mar 27, 2013 at 14:56
\$\endgroup\$
1
\$\begingroup\$

Programmers spend almost all their time reading code; code should be documented. API users need good documentation too.

A meaningless name like foo is the first red flag; good names are an excellent form of code documentation.

Go has a documentation tool: Godoc: documenting Go code. "Documentation is a huge part of making software accessible and maintainable."

Here's my solution:

// A Tour of Go. Exercise 40: Maps.
package main
import (
 "code.google.com/p/go-tour/wc"
 "strings"
)
// WordCount returns a map of the counts of each "word" in the string s.
func WordCount(s string) map[string]int {
 counts := make(map[string]int)
 for _, word := range strings.Fields(s) {
 counts[word]++
 }
 return counts
}
func main() {
 wc.Test(WordCount)
}
answered Mar 28, 2013 at 14:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.