Add reduction code
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package hmm
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
// CountNSort consumes a stream of strings, calculates counts of occurances in
|
||||
// the stream. After the stream is closed it sorts the unique keys by frequency
|
||||
// and returns it as a Results.
|
||||
func CountNSort(in <-chan string) Results {
|
||||
res := map[string]int{}
|
||||
|
||||
for i := range in {
|
||||
res[i]++
|
||||
}
|
||||
|
||||
r := Results{}
|
||||
for k, v := range res {
|
||||
r = append(r, Result{k, v})
|
||||
}
|
||||
|
||||
sort.Sort(r)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// Result encodes a frequency for seen string.
|
||||
type Result struct {
|
||||
Key string
|
||||
Count int
|
||||
}
|
||||
|
||||
// Results exists to sort a slice of Result
|
||||
type Results []Result
|
||||
|
||||
func (r Results) Len() int { return len(r) }
|
||||
func (r Results) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
|
||||
func (r Results) Less(i, j int) bool { return r[i].Count < r[j].Count }
|
||||
Reference in New Issue
Block a user