generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtop.go
49 lines (36 loc) · 886 Bytes
/
top.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
package hw03frequencyanalysis
import (
"sort"
"strings"
)
type wordCount struct {
word string
count int
}
func Top10(input string) []string {
wordCountsMap := make(map[string]int)
for _, word := range strings.Fields(input) {
wordCountsMap[word]++
}
wordCounts := make([]wordCount, 0, len(wordCountsMap))
for word, count := range wordCountsMap {
wordCounts = append(wordCounts, wordCount{word, count})
}
sort.Slice(wordCounts, func(i, j int) bool {
if wordCounts[i].count == wordCounts[j].count {
return wordCounts[i].word < wordCounts[j].word
}
return wordCounts[i].count > wordCounts[j].count
})
var topWords []wordCount
if len(wordCounts) >= 10 {
topWords = wordCounts[:10]
} else {
topWords = wordCounts
}
result := make([]string, 0, len(topWords))
for _, wc := range topWords {
result = append(result, wc.word)
}
return result
}