-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmost_frequent_words_map_slice.go
53 lines (43 loc) · 1.07 KB
/
most_frequent_words_map_slice.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"fmt"
)
/*Implement the MostPopularWord(words []string) string function, which returns the most frequently occurring word in the slice.
If there are several such words, then the first one is returned.*/
func main() {
words := []string{"one", "two", "three", "four", "five"}
fmt.Println(MostPopularWord(words))
}
func MostPopularWord(words []string) string {
words_map := map[string]int{}
vmax := 0
for i := 0; i < len(words); i++ {
w, found := words_map[words[i]]
if found {
words_map[words[i]] = w + 1
} else {
words_map[words[i]] = 1
}
}
///
for _, v := range words_map {
if v > vmax {
vmax = v
}
}
///
if vmax > 0 {
for key, val := range words_map {
if val == vmax {
return key
}
}
}
return "rip"
}
/*
1. generate a new map "string - number"
2. if the word has not yet been found, add it to the map.
3. if found - find it by key in the map and increment the val.
4. search for the highest val & return it's key
the order of the keys in the map is randomized...*/