1

Having a hard time trying to figure out how can I count the number of apps or words on a slice using the go-lang code I made.

Hoping someone could help me figure out how to count the number of occurence?

https://play.golang.org/p/KvgI-lCz_c6

package main

import (
    "fmt"
)

func main() {

    apps := []string{"one", "two", "three", "one", "four"}
    fmt.Println("apps:", apps)

    o := CountOccurence(apps)

    fmt.Println("=== o: ", o)

}

func CountOccurence(apps []string) map[string]int {

    dict := make(map[string]int)
    for k, v := range apps {
        fmt.Println(k, v)

        dict[v] = k
    }

    // fmt.Println("=== dict: ", dict)

    return dict
}

Outputs the following

apps: [one two three one four]
0 one
1 two
2 three
3 one
4 four
=== o:  map[four:4 one:3 three:2 two:1]

PS: go strings.Count only counts a string, not a []string.

1 Answer 1

5

What you currently do is you gather the different elements and you assign their index to them. If a word occurs multiple times, the highest index will be assigned to it.

As you stated, you want to count the words. So instead of the index, assign 1 for new words (first occurrence), and if it's already in the map, increment its value by 1.

Since you can index a map with a non-existing key, in which case the result is the zero value of the value type of the map, which is 0 for int, it will tell you it was found 0 times (so far), so you don't even have to check if a key is already in there, just go ahead and increment it:

dict[v]++

So CountOccurrences() may look like this:

func CountOccurence(apps []string) map[string]int {
    dict := make(map[string]int)
    for _, v := range apps {
        fmt.Println(v)
        dict[v]++
    }
    return dict
}

Which will output (try it on the Go Playground):

apps: [one two three one four]
one
two
three
one
four
=== o:  map[four:1 one:2 three:1 two:1]
1
  • Thank you for your amazing explanation! And did not knew go could do that, I learned a lot here. Thanks again! Jan 26, 2021 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.