Created
September 4, 2018 02:41
-
-
Save bsolomon1124/a95aa367c727a5c2250599477d4a2496 to your computer and use it in GitHub Desktop.
Mimic Python's collection.Counter in Go - attempt 2
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 counter | |
| import ( | |
| "fmt" | |
| "sort" | |
| ) | |
| type kv struct { | |
| Key int | |
| Value int | |
| } | |
| type Counter interface { | |
| Counts() map[int]int | |
| MostCommon(n int) map[int]int | |
| } | |
| type IntCounter []int | |
| func (ic IntCounter) Counts() map[int]int { | |
| counts := make(map[int]int) | |
| for _, i := range ic { | |
| counts[i]++ | |
| } | |
| return counts | |
| } | |
| func (ic IntCounter) MostCommon(n int) map[int]int { | |
| counts := ic.Counts() | |
| // A slice of (Key, Value) structs | |
| var ss []kv | |
| for k, v := range counts { | |
| ss = append(ss, kv{k, v}) | |
| } | |
| // Greatest to smallest, by value | |
| // Sort the provided slice given the provided "less" function | |
| sort.Slice(ss, func(i, j int) bool { return ss[i].Value > ss[j].Value }) | |
| result := make(map[int]int) | |
| for i:= 0; i < n; i++ { | |
| pair := ss[i] | |
| result[pair.Key] = pair.Value | |
| } | |
| return result | |
| } | |
| func main() { | |
| ic := IntCounter([]int{1, 1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7, 7}) | |
| fmt.Println(ic.MostCommon(m, 3)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment