Skip to content

Instantly share code, notes, and snippets.

@uraimo
Created June 2, 2013 09:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uraimo/5693171 to your computer and use it in GitHub Desktop.
Save uraimo/5693171 to your computer and use it in GitHub Desktop.
A Tour of Go: Maps Exercise solution w/o strings.Fields
package main
import (
"code.google.com/p/go-tour/wc"
)
func WordCount(s string) map[string]int {
res := make(map[string]int);
str := make([]rune,0,10)
for _, r := range(s){
if r == ' ' {
res[string(str)]++
str = make([]rune,0,10)
}else{
str = append(str,r)
}
}
res[string(str)]++
return res
}
func main() {
wc.Test(WordCount)
}
@uraimo
Copy link
Author

uraimo commented Jun 2, 2013

Used unicode.IsSpace instead. Still don't like the fact that a new rune array/slice must be allocated every time a token ends, since slices can't use negative indexes i guess this is the only option...

package main

import (
    "code.google.com/p/go-tour/wc"
    "unicode"
)

func WordCount(s string) map[string]int {
    res := make(map[string]int);
    str := make([]rune,0,10)
    for _, r := range(s){
        if unicode.IsSpace(r) {
            res[string(str)]++
            str = make([]rune,0,10)
        }else{
            str = append(str,r)
        }
    }
    res[string(str)]++
    return res

}

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

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