-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
72 lines (60 loc) · 1.41 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package decide
import (
"bytes"
"fmt"
"sort"
)
// FrequencySorter
// Sorts Frequency Lists not thread-safe
type FrequencySorter struct {
frequencies map[string]int
list []string
}
func NewFrequencySorter() FrequencySorter {
return FrequencySorter{
frequencies: make(map[string]int),
list: nil,
}
}
func (t FrequencySorter) Sort(list []string) {
t.list = list
sort.Sort(t)
}
func (t FrequencySorter) SortReverse(list []string) {
t.list = list
sort.Sort(sort.Reverse(t))
}
func (t FrequencySorter) FrequencyList() []string {
list := make([]string, 0, len(t.frequencies))
for key, _ := range t.frequencies {
list = append(list, key)
}
t.SortReverse(list)
return list
}
func (t FrequencySorter) AddToFrequencies(str string) {
t.frequencies[str]++
}
func (t FrequencySorter) AddValue(str string, count int) {
t.frequencies[str] = count
}
func (t FrequencySorter) Len() int {
return len(t.list)
}
func (t FrequencySorter) Less(i, j int) bool {
if t.frequencies[t.list[i]] == t.frequencies[t.list[j]] {
return t.list[i] < t.list[j]
}
return t.frequencies[t.list[i]] < t.frequencies[t.list[j]]
}
func (t FrequencySorter) Swap(i, j int) {
t.list[i], t.list[j] = t.list[j], t.list[i]
}
func (t FrequencySorter) String() string {
buf := &bytes.Buffer{}
fmt.Fprintln(buf, "Frequency Table:")
for key, val := range t.frequencies {
fmt.Fprintf(buf, "% 4d: %s\n", val, key)
}
return buf.String()
}