From acd1263604d8804ff6d54fa7b74b03bcdbe1a56b Mon Sep 17 00:00:00 2001 From: "Stephen McQuay (work)" Date: Thu, 15 Jun 2017 15:19:49 -0700 Subject: [PATCH] Add reduction code --- count.go | 38 ++++++++++++++++++++++++++++++++++++++ count_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 count.go create mode 100644 count_test.go diff --git a/count.go b/count.go new file mode 100644 index 0000000..d834d24 --- /dev/null +++ b/count.go @@ -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 } diff --git a/count_test.go b/count_test.go new file mode 100644 index 0000000..7d58afb --- /dev/null +++ b/count_test.go @@ -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 +}