Last active
July 12, 2022 21:13
-
-
Save sshaplygin/e9fd99cda4a7ca283a51253544534e28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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