Skip to content

Commit d937386

Browse files
committed
[feature]: complete hw3
1 parent 0f4791f commit d937386

File tree

4 files changed

+52
-4
lines changed

4 files changed

+52
-4
lines changed

hw03_frequency_analysis/.sync

Whitespace-only changes.

hw03_frequency_analysis/go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
module github.com/fixme_my_friend/hw03_frequency_analysis
1+
module github.com/kpechenenko/otus-go-hw/hw03_frequency_analysis
22

33
go 1.19
44

hw03_frequency_analysis/top.go

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,38 @@
11
package hw03frequencyanalysis
22

3-
func Top10(_ string) []string {
4-
// Place your code here.
5-
return nil
3+
import (
4+
"sort"
5+
"strings"
6+
)
7+
8+
func Top10(s string) []string {
9+
if len(s) == 0 {
10+
return []string{}
11+
}
12+
words := strings.Fields(s)
13+
if len(words) == 0 {
14+
return []string{}
15+
}
16+
frequency := make(map[string]int)
17+
for _, w := range words {
18+
frequency[w]++
19+
}
20+
uniqueWords := make([]string, 0)
21+
for w := range frequency {
22+
uniqueWords = append(uniqueWords, w)
23+
}
24+
sort.Slice(
25+
uniqueWords,
26+
func(i, j int) bool {
27+
diff := frequency[uniqueWords[i]] - frequency[uniqueWords[j]]
28+
if diff == 0 {
29+
return strings.Compare(uniqueWords[i], uniqueWords[j]) < 0
30+
}
31+
return diff > 0
32+
})
33+
topLimit := 10
34+
if len(uniqueWords) <= topLimit {
35+
return uniqueWords
36+
}
37+
return uniqueWords[:topLimit]
638
}

hw03_frequency_analysis/top_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,19 @@ func TestTop10(t *testing.T) {
8080
}
8181
})
8282
}
83+
84+
func TestTop10_9Elems(t *testing.T) {
85+
s := "a b b c c c d d d d e e e e e f f f f f f g g g g g g g"
86+
expected := []string{"g", "f", "e", "d", "c", "b", "a"}
87+
t.Run("9 letters in reverse alphabetic orders", func(t *testing.T) {
88+
require.Equal(t, expected, Top10(s))
89+
})
90+
}
91+
92+
func TestTop10_Only1Elems(t *testing.T) {
93+
s := "a"
94+
expected := []string{"a"}
95+
t.Run("only 1 letter", func(t *testing.T) {
96+
require.Equal(t, expected, Top10(s))
97+
})
98+
}

0 commit comments

Comments
 (0)