Skip to content

Instantly share code, notes, and snippets.

@sshaplygin
Last active July 12, 2022 21:13
Show Gist options
  • Select an option

  • Save sshaplygin/e9fd99cda4a7ca283a51253544534e28 to your computer and use it in GitHub Desktop.

Select an option

Save sshaplygin/e9fd99cda4a7ca283a51253544534e28 to your computer and use it in GitHub Desktop.
package hw03frequencyanalysis
import (
"regexp"
"sort"
)
var r = regexp.MustCompile(`\s+`)
func Top10(text string) []string {
if len(text) == 0 {
return nil
}
wordsMap := make(map[string]int)
words := r.Split(text, -1)
for _, word := range words {
wordsMap[word]++
}
result := make([]string, 0, len(wordsMap))
for name := range wordsMap {
result = append(result, name)
}
sort.Slice(result, func(i, j int) bool {
first := result[i]
second := result[j]
if wordsMap[first] == wordsMap[second] {
return first < second
}
return wordsMap[first] > wordsMap[second]
})
return result[:10]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment