-
Notifications
You must be signed in to change notification settings - Fork 0
/
copeland.go
238 lines (206 loc) · 4.33 KB
/
copeland.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package copeland
import (
"cmp"
"errors"
"fmt"
"slices"
)
type Scoring struct {
Win float64
Tie float64
Loss float64
}
var DefaultScoring = &Scoring{
Win: 1,
Tie: .5,
Loss: 0,
}
type ScoreEntry struct {
Name string
Score float64
}
type Matrix struct {
data []int64
size int
}
func NewMatrix(size int) *Matrix {
if size < 0 {
panic("negative matrix size!")
}
return &Matrix{
data: make([]int64, size*size),
size: size,
}
}
func (m *Matrix) Size() int {
return m.size
}
func (m *Matrix) Add(o *Matrix) *Matrix {
if m.Size() != o.Size() {
panic("sizes are not equal!")
}
for i := range m.data {
m.data[i] += o.data[i]
}
return m
}
func (m *Matrix) Get(i, j int) int64 {
return m.data[i*m.size+j]
}
func (m *Matrix) Set(i, j int, value int64) {
m.data[i*m.size+j] = value
}
func (m *Matrix) Inc(i, j int) {
m.data[i*m.size+j]++
}
func (m *Matrix) Row(i int) []int64 {
return m.data[i*m.size : (i+1)*m.size]
}
type Copeland struct {
names []string
state *Matrix
}
func New(names []string) (*Copeland, error) {
copied := make([]string, len(names))
copy(copied, names)
slices.Sort(copied)
copied = slices.Compact(copied)
if len(copied) < 2 {
return nil, errors.New("not enough alternatives")
}
return &Copeland{
names: copied,
state: NewMatrix(len(copied)),
}, nil
}
func (c *Copeland) nameToIndex(name string) (int, bool) {
return slices.BinarySearch(c.names, name)
}
var ErrIncorrectLength = errors.New("incorrect number of items in ballot list")
type UnknownNameError string
func (e UnknownNameError) Error() string {
return fmt.Sprintf("unknown name \"%s\" in ballot", string(e))
}
func (e UnknownNameError) Name() string {
return string(e)
}
type MissingNameError string
func (e MissingNameError) Error() string {
return fmt.Sprintf("missing name \"%s\" in ballot", string(e))
}
func (e MissingNameError) Name() string {
return string(e)
}
type DuplicateNameError struct {
name string
count int
}
func (e DuplicateNameError) Error() string {
return fmt.Sprintf("name \"%s\" appears %d times in ballot", e.name, e.count)
}
func (e DuplicateNameError) Name() string {
return e.name
}
func (e DuplicateNameError) Count() int {
return e.count
}
func (c *Copeland) ballotToMatrix(ballot []string) (*Matrix, error) {
size := len(c.names)
if len(ballot) != size {
return nil, ErrIncorrectLength
}
mapped := make([]int, size)
counts := make([]int, size)
for i, name := range ballot {
mappedName, ok := c.nameToIndex(name)
if !ok {
return nil, UnknownNameError(name)
}
mapped[i] = mappedName
counts[mappedName]++
}
for i, count := range counts {
switch count {
case 0:
return nil, MissingNameError(c.names[i])
case 1:
default:
return nil, DuplicateNameError{
name: c.names[i],
count: count,
}
}
}
m := NewMatrix(size)
for base, winner := range mapped {
for _, loser := range mapped[base+1:] {
m.Inc(winner, loser)
}
}
return m, nil
}
func (c *Copeland) Update(ballot []string) error {
matrix, err := c.ballotToMatrix(ballot)
if err != nil {
return fmt.Errorf("state update failed: %w", err)
}
c.state.Add(matrix)
return nil
}
func (c *Copeland) Score(scoring *Scoring) []ScoreEntry {
if scoring == nil {
scoring = DefaultScoring
}
size := c.state.Size()
res := make([]ScoreEntry, 0, size)
for i := 0; i < size; i++ {
score := float64(0)
for j := 0; j < size; j++ {
if i == j {
continue
}
runner := c.state.Get(i, j)
opponent := c.state.Get(j, i)
switch {
case runner > opponent:
score += scoring.Win
case runner < opponent:
score += scoring.Loss
default:
score += scoring.Tie
}
}
res = append(res, ScoreEntry{
Name: c.names[i],
Score: score,
})
}
return res
}
func CmpScoreEntry(a, b ScoreEntry) int {
if n := cmp.Compare(b.Score, a.Score); n != 0 {
return n
}
return cmp.Compare(a.Name, b.Name)
}
func RankScore(scores []ScoreEntry) [][]ScoreEntry {
copied := make([]ScoreEntry, len(scores))
copy(copied, scores)
slices.SortFunc(copied, CmpScoreEntry)
return groupBy(copied, func(a, b ScoreEntry) bool { return a.Score == b.Score })
}
func groupBy[S ~[]E, E any](s S, eq func(E, E) bool) []S {
var head []S
for len(s) > 0 {
key := s[0]
var idx int
for idx = 1; idx < len(s); idx++ {
if !eq(s[idx], key) {
break
}
}
head = append(head, s[0:idx])
s = s[idx:]
}
return head
}