Skip to content

Instantly share code, notes, and snippets.

@bsolomon1124
Created September 4, 2018 02:41
Show Gist options
  • Select an option

  • Save bsolomon1124/a95aa367c727a5c2250599477d4a2496 to your computer and use it in GitHub Desktop.

Select an option

Save bsolomon1124/a95aa367c727a5c2250599477d4a2496 to your computer and use it in GitHub Desktop.
Mimic Python's collection.Counter in Go - attempt 2
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