Add reduction code
This commit is contained in:
parent
899329aa54
commit
acd1263604
38
count.go
Normal file
38
count.go
Normal file
@ -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 }
|
42
count_test.go
Normal file
42
count_test.go
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
package hmm
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestCountNSort(t *testing.T) {
|
||||||
|
in := []string{"b", "c", "c", "a", "b", "c"}
|
||||||
|
|
||||||
|
ch := make(chan string)
|
||||||
|
go func() {
|
||||||
|
for _, i := range in {
|
||||||
|
ch <- i
|
||||||
|
}
|
||||||
|
close(ch)
|
||||||
|
}()
|
||||||
|
|
||||||
|
got := CountNSort(ch)
|
||||||
|
want := Results{
|
||||||
|
{"a", 1},
|
||||||
|
{"b", 2},
|
||||||
|
{"c", 3},
|
||||||
|
}
|
||||||
|
|
||||||
|
if !EqualResults(got, want) {
|
||||||
|
t.Fatalf("unequal Results: got %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func EqualResults(a, b Results) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < len(a); i++ {
|
||||||
|
if a[i].Key != b[i].Key {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if a[i].Count != b[i].Count {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user