Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion hw03_frequency_analysis/go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module github.com/fixme_my_friend/hw03_frequency_analysis
module github.com/ezhk/golang-learning/hw03_frequency_analysis

go 1.14

Expand Down
50 changes: 47 additions & 3 deletions hw03_frequency_analysis/top.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,50 @@
package hw03_frequency_analysis //nolint:golint,stylecheck

func Top10(_ string) []string {
// Place your code here
return nil
import (
"regexp"
"sort"
"strings"
"unicode"
)

var ignoredSymbols = regexp.MustCompile(`[-]`)

type WordFrequency struct {
word string
RepeatCounter int
}

func Top10(inputLine string) []string {
const MaxLength = 10
mostFrequentWords := make([]string, 0, MaxLength)

// prepare map with counter
freqMap := make(map[string]int)
inputLine = ignoredSymbols.ReplaceAllString(inputLine, "")
for _, word := range strings.FieldsFunc(inputLine, splitFunc) {
freqMap[strings.ToLower(word)]++
}

// convert map to slice wordFrequency for next sorting
wordSlice := make([]WordFrequency, 0, len(freqMap))
for word, counter := range freqMap {
wordSlice = append(wordSlice, WordFrequency{word, counter})
}
sort.Slice(wordSlice, func(i, j int) bool {
return wordSlice[i].RepeatCounter > wordSlice[j].RepeatCounter
})

// store data
for _, value := range wordSlice {
if len(mostFrequentWords) >= MaxLength {
break
}
mostFrequentWords = append(mostFrequentWords, value.word)
}

return mostFrequentWords
}

func splitFunc(char rune) bool {
return unicode.IsPunct(char) || unicode.IsSpace(char)
}
25 changes: 24 additions & 1 deletion hw03_frequency_analysis/top_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

// Change to true if needed
var taskWithAsteriskIsCompleted = false
var taskWithAsteriskIsCompleted = true

var text = `Как видите, он спускается по лестнице вслед за своим
другом Кристофером Робином, головой вниз, пересчитывая
Expand Down Expand Up @@ -58,3 +58,26 @@ func TestTop10(t *testing.T) {
}
})
}

func TestExtendedTop10(t *testing.T) {
type test struct {
text string
expected []string
}
for _, testCase := range []test{
{"какой-то", []string{"какойто"}},
{"кот,собака собака", []string{"собака", "кот"}},
// check ingoring "-" in next test
{"12 1-2 5", []string{"12", "5"}},
{"1\n, ;1 -1 \t2,2 3.", []string{"1", "2", "3"}},
} {
result := Top10(testCase.text)
assert.Equal(t, result, testCase.expected)
}
}

func BenchmarkTop(b *testing.B) {
for i := 0; i < b.N; i++ {
Top10(text)
}
}