How can i get top 3 most popular words from []string

https://play.golang.org/p/4KqiG6MR5Id
how can i get top N used words in a []string w/o getting the other words? commented in the code how the result might look like.
This is what it looks like just for counting. But im trying to get the top 3 frequent words
https://play.golang.org/p/Jr8SyZjpi_l

2 Likes
  1. Modify rangeMap to receive a parameter that indicates how many top values you want to return

  2. Use this code

    func rangeMap(s []string, count int) map[string]int {
        words := strings.Split(strings.Join(s, ""), " ")
    
     // count occurences	
     m := make(map[string]int)
     for _, word := range words {
     	_, ok := m[word]
     	if !ok {
     	  m[word] = 1
     	} else {
     	  m[word]++
     	}
     }
     
     // Takes max values
     counts:= make(map[string]int)
     for key, value := range m {
        if value > 0  {
            counts[key] = value
        }
     }
     
     // Sorts By Value
     keys := make([]string, 0, len(counts))
     for key := range counts {
     	keys = append(keys, key)
     }
     sort.Slice(keys, func(i, j int) bool { return counts[keys[i]] > counts[keys[j]] })
    
     // Builds result map	
     result := make(map[string]int)
     for _, key := range keys {
        result[key] = counts[key]
        count--
        if count == 0 {
           break
        }	
    
     }
     return result
     }
3 Likes

Thanks for the solution, but im not really sure what is happening here after we range over our sorted []string.
The results part

2 Likes

Ok
After sort the keys, we will build a map to return the results to the caller. This code is

// Builds result map
result := make(map[string]int)
for _, key := range keys {
	result[key] = counts[key]
	count--
	if count == 0 {
		break
	}
}
return result

/count is the number of items you want to return. You mention 3 top, so count is that number.
However, the tricky part is the sort

// Takes max values
	counts := make(map[string]int)
	for key, value := range m {
		if value > 1 {
			counts[key] = value
		}
	}

This part takes only the words that are repeated in the string. I wrote 0 (value > 0) but the number should be 1 (value > 1)

Afther this, we build a slice with the keys of the above map. The sort routune takes the count of each of those keys to order this slice.

3 Likes

Here it is: https://play.golang.org/p/UeegCwmMUbV

You correctly identified the first part of the solution. You first need to count the words and for this you use a map.

What is missing, is the second step. To get the three most frequent words, you need to sort the words by count. For this you need a slice of word-count pairs that you may then sort.

Once the slice is sorted, the three first entries is what you want to print.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.