Skip to content

Instantly share code, notes, and snippets.

@MattSurabian
Created July 14, 2013 04:52
Show Gist options
  • Save MattSurabian/5993259 to your computer and use it in GitHub Desktop.
Save MattSurabian/5993259 to your computer and use it in GitHub Desktop.
My implementation of WordCount in Go. Part of the Go tour: http://tour.golang.org/#40
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
words := strings.Fields(s)
wordCountMap := make(map[string]int)
for _,word := range words{
wordCountMap[word]++
}
return wordCountMap
}
func main() {
wc.Test(WordCount)
}
@geekodour
Copy link

geekodour commented Dec 8, 2018

that's a very nice solution, i came up with a rather ugly one.

package main

import (
	"golang.org/x/tour/wc"
	"strings"
)

func WordCount(s string) map[string]int {
	ss := strings.Fields(s)
	m := map[string]int{}
	for i, v := range ss {
		if _, ok := m[v]; !ok {
			count := 1
			for _, u := range ss[i+1:] {
				if v == u {
					count++
				}
			}
			m[v] = count
		}
	}
	return m
}

func main() {
	wc.Test(WordCount)
}

@vishuvenu
Copy link

package main

import (
	"golang.org/x/tour/wc"
	"strings"
)

func WordCount(s string) map[string]int {
	wc := make(map[string]int)
	
	for _, word := range strings.Split(s, " ") {
		if _, exist := wc[word]; !exist {
			wc[word] = 0
		}
		
		wc[word] += 1
	}
	return wc
}

func main() {
	wc.Test(WordCount)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment