Created
February 4, 2025 23:01
-
-
Save brettmilford/6340df164e0a81ffdb982f462c83c65b 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 main | |
| import ( | |
| "bufio" | |
| "fmt" | |
| "os" | |
| "sort" | |
| ) | |
| type WordCount struct { | |
| count int | |
| word string | |
| } | |
| func main() { | |
| scanner := bufio.NewScanner(os.Stdin) | |
| scanner.Split(bufio.ScanWords) | |
| wordMap := make(map[string]int) | |
| for scanner.Scan() { | |
| word := scanner.Text() | |
| _, ok := wordMap[word] | |
| if ok { | |
| wordMap[word] += 1 | |
| } else { | |
| wordMap[word] = 1 | |
| } | |
| } | |
| if err := scanner.Err(); err != nil { | |
| fmt.Fprintln(os.Stderr, "reading standard input:", err) | |
| } | |
| wordCountStruct := new(WordCount) | |
| wordCountSlice := make([]WordCount, len(wordMap)) | |
| i := 0 | |
| for key, value := range wordMap { | |
| wordCountStruct.count = value | |
| wordCountStruct.word = key | |
| wordCountSlice[i] = *wordCountStruct | |
| i++ | |
| } | |
| sort.Slice(wordCountSlice, func(i, j int) bool { return wordCountSlice[i].count < wordCountSlice[j].count }) | |
| topTen := wordCountSlice[len(wordCountSlice)-10:] | |
| for _, element := range topTen { | |
| fmt.Printf("%4d %s\n", element.count, element.word) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment