-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathvote.go
96 lines (92 loc) · 1.97 KB
/
vote.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright (c) 2021, The Emergent Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package decoder
import (
"math/rand"
"sort"
)
// TopVoteInt returns the choice with the most votes among a list of votes
// as integer-valued choices, and also returns the number of votes for that item.
// In the case of ties, it chooses one at random (otherwise it would have a bias
// toward the lowest numbered item).
func TopVoteInt(votes []int) (int, int) {
sort.Ints(votes)
prv := votes[0]
cur := prv
top := prv
topn := 1
curn := 1
n := len(votes)
var ties []int
for i := 1; i < n; i++ {
cur = votes[i]
if cur != prv {
if curn > topn {
top = prv
topn = curn
ties = []int{top}
} else if curn == topn {
ties = append(ties, prv)
}
curn = 1
prv = cur
} else {
curn++
}
}
if curn > topn {
top = cur
topn = curn
ties = []int{top}
} else if curn == topn {
ties = append(ties, cur)
}
if len(ties) > 1 {
ti := rand.Intn(len(ties))
top = ties[ti]
}
return top, topn
}
// TopVoteString returns the choice with the most votes among a list of votes
// as string-valued choices, and also returns the number of votes for that item.
// In the case of ties, it chooses one at random (otherwise it would have a bias
// toward the lowest numbered item).
func TopVoteString(votes []string) (string, int) {
sort.Strings(votes)
prv := votes[0]
cur := prv
top := prv
topn := 1
curn := 1
n := len(votes)
var ties []string
for i := 1; i < n; i++ {
cur = votes[i]
if cur != prv {
if curn > topn {
top = prv
topn = curn
ties = []string{top}
} else if curn == topn {
ties = append(ties, prv)
}
curn = 1
prv = cur
} else {
curn++
}
}
if curn > topn {
top = cur
topn = curn
ties = []string{top}
} else if curn == topn {
ties = append(ties, cur)
}
if len(ties) > 1 {
ti := rand.Intn(len(ties))
top = ties[ti]
}
return top, topn
}