-
Notifications
You must be signed in to change notification settings - Fork 1
/
averages-mode-4.go
67 lines (59 loc) · 1.21 KB
/
averages-mode-4.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
package main
import "fmt"
type collection interface {
iterator() func() (interface{}, bool)
}
type intSlice []int
func (s intSlice) iterator() func() (interface{}, bool) {
i := 0
return func() (interface{}, bool) {
if i >= len(s) {
return 0, false
}
v := s[i]
i++
return v, true
}
}
type runeList string
func (s runeList) iterator() func() (interface{}, bool) {
c := make(chan rune)
go func() {
for _, r := range s {
c <- r
}
close(c)
}()
return func() (interface{}, bool) {
r, ok := <-c
return string(r), ok
}
}
func main() {
fmt.Println(mode(intSlice{2, 7, 1, 8, 2}))
fmt.Println(mode(runeList("Enzyklopädie")))
}
func mode(a collection) []interface{} {
m := make(map[interface{}]int)
i := a.iterator()
for {
v, ok := i()
if !ok {
break
}
m[v]++
}
var mode []interface{}
var n int
for k, v := range m {
switch {
case v < n:
case v > n:
n = v
mode = append(mode[:0], k)
default:
mode = append(mode, k)
}
}
return mode
}