summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGianni Ceccarelli <gianni.ceccarelli@broadbean.com>2019-08-01 12:03:11 +0100
committerGianni Ceccarelli <gianni.ceccarelli@broadbean.com>2019-08-01 12:03:11 +0100
commit2f2f4bff5fa2a10fe9ebf551af3d6e9434e1b928 (patch)
tree88c5e4fb1f97461b499312752873f936196d6ade
parentother half of JS implementation (diff)
downloadmixed-server-2f2f4bff5fa2a10fe9ebf551af3d6e9434e1b928.tar.gz
mixed-server-2f2f4bff5fa2a10fe9ebf551af3d6e9434e1b928.tar.bz2
mixed-server-2f2f4bff5fa2a10fe9ebf551af3d6e9434e1b928.zip
go model
-rw-r--r--go/mixed-server.go63
-rw-r--r--go/mixed-server_test.go24
2 files changed, 87 insertions, 0 deletions
diff --git a/go/mixed-server.go b/go/mixed-server.go
new file mode 100644
index 0000000..44dfcdc
--- /dev/null
+++ b/go/mixed-server.go
@@ -0,0 +1,63 @@
+package main
+
+import (
+ "sort"
+ "sync"
+)
+
+type wordsByCount struct {
+ words *map[string]uint
+ keys []string
+}
+
+func newWordsByCount(w *map[string]uint) wordsByCount {
+ keys := make([]string, len(*w))
+ i := 0
+ for w, _ := range *w {
+ keys[i] = w
+ i++
+ }
+
+ return wordsByCount{words: w, keys: keys}
+}
+func (wbc wordsByCount) Len() int { return len(*wbc.words) }
+func (wbc wordsByCount) Swap(i, j int) {
+ wbc.keys[i], wbc.keys[j] = wbc.keys[j], wbc.keys[i]
+}
+func (wbc wordsByCount) Less(i, j int) bool {
+ return (*wbc.words)[wbc.keys[i]] > (*wbc.words)[wbc.keys[j]]
+}
+func (wbc wordsByCount) MostCommonWords() []string {
+ sort.Sort(wbc)
+ mcw := make([]string, len(*wbc.words))
+ for i, p := range wbc.keys {
+ mcw[i] = p
+ }
+ return mcw
+}
+
+type Model struct {
+ lock sync.RWMutex
+ words map[string]uint
+}
+
+func NewModel() Model {
+ return Model{words: make(map[string]uint)}
+}
+
+func (m *Model) AddWords(words []string) {
+ m.lock.Lock()
+ defer m.lock.Unlock()
+ for _, word := range words {
+ v, _ := m.words[word]
+ m.words[word] = v + 1
+ }
+}
+
+func (m *Model) GetMostCommonPairs(how_many uint) []string {
+ m.lock.RLock()
+ defer m.lock.RUnlock()
+ wbc := newWordsByCount(&m.words)
+ mcw := wbc.MostCommonWords()
+ return mcw[:how_many]
+}
diff --git a/go/mixed-server_test.go b/go/mixed-server_test.go
new file mode 100644
index 0000000..6e33b1f
--- /dev/null
+++ b/go/mixed-server_test.go
@@ -0,0 +1,24 @@
+package main
+
+import (
+ "testing"
+)
+
+func TestModel1(t *testing.T) {
+ m := NewModel()
+ m.AddWords([]string{"a", "b", "a"})
+ got := m.GetMostCommonPairs(2)
+ if !(got[0] == "a" && got[1] == "b") {
+ t.Errorf("bad order, got %v", got)
+ }
+}
+
+func TestModel2(t *testing.T) {
+ m := NewModel()
+ m.AddWords([]string{"a", "b", "a"})
+ m.AddWords([]string{"b", "c", "b"})
+ got := m.GetMostCommonPairs(2)
+ if !(got[0] == "b" && got[1] == "a") {
+ t.Errorf("bad order, got %v", got)
+ }
+}