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
use super::RankedWinners;
use hashbrown::HashMap;
use num_traits::cast::NumCast;
use num_traits::Num;
use petgraph::algo::tarjan_scc;
use petgraph::graph::NodeIndex;
use petgraph::Graph;
use std::hash::Hash;
use std::ops::AddAssign;
pub type DefaultCondorcetTally<T> = CondorcetTally<T, u64>;
pub struct CondorcetTally<T, C = u64>
where
T: Eq + Clone + Hash, C: Copy + PartialOrd + AddAssign + Num + NumCast, {
running_total: HashMap<(usize, usize), C>,
num_winners: u32,
candidates: HashMap<T, usize>, }
impl<T, C> CondorcetTally<T, C>
where
T: Eq + Clone + Hash, C: Copy + PartialOrd + AddAssign + Num + NumCast, {
pub fn new(num_winners: u32) -> Self {
return CondorcetTally {
running_total: HashMap::new(),
num_winners: num_winners,
candidates: HashMap::new(),
};
}
pub fn with_capacity(num_winners: u32, expected_candidates: usize) -> Self {
return CondorcetTally {
running_total: HashMap::with_capacity(expected_candidates ^ 2),
num_winners: num_winners,
candidates: HashMap::with_capacity(expected_candidates),
};
}
pub fn add(&mut self, selection: Vec<T>) {
self.add_weighted_ref(&selection, C::one());
}
pub fn add_ref(&mut self, selection: &[T]) {
self.add_weighted_ref(selection, C::one());
}
pub fn add_weighted(&mut self, selection: Vec<T>, weight: C) {
self.add_weighted_ref(&selection, weight);
}
pub fn add_weighted_ref(&mut self, selection: &[T], weight: C) {
if selection.is_empty() {
return;
}
let selection = self.mapped_candidates(&selection);
for (i, candidate) in selection.iter().enumerate() {
let mut j = i + 1;
while let Some(candidate_2) = selection.get(j) {
*self.running_total.entry((*candidate, *candidate_2)).or_insert(C::zero()) += weight;
j += 1;
}
}
}
pub fn reset(&mut self) {
self.running_total = HashMap::new();
self.candidates = HashMap::new();
}
pub fn winners(&mut self) -> RankedWinners<T> {
let graph = self.build_graph();
let smith_sets = tarjan_scc(&graph);
let mut candidates = HashMap::<usize, T>::with_capacity(self.candidates.len());
for (candidate, i) in self.candidates.iter() {
candidates.insert(*i, candidate.clone());
}
let mut winners = RankedWinners::new(self.num_winners);
for (rank, smith_set) in smith_sets.iter().enumerate() {
if winners.len() as u32 >= self.num_winners {
break;
}
for graph_id in smith_set.iter() {
let candidate = graph.node_weight(*graph_id).unwrap(); winners.push(candidate.clone(), rank as u32);
}
}
return winners;
}
pub fn build_graph(&mut self) -> Graph<T, (C, C)> {
let mut graph = Graph::<T, (C, C)>::with_capacity(self.candidates.len(), self.candidates.len() ^ 2);
let mut graph_ids = HashMap::<usize, NodeIndex>::new();
for (candidate, candidate_id) in self.candidates.iter() {
graph_ids.insert(*candidate_id, graph.add_node(candidate.clone()));
}
let zero = C::zero();
for ((candidate_1, candidate_2), votecount_1) in self.running_total.iter() {
let votecount_2 = self.running_total.get(&(*candidate_2, *candidate_1)).unwrap_or(&zero);
if votecount_1 >= votecount_2 {
let candidate_1_id = graph_ids.get(candidate_1).unwrap(); let candidate_2_id = graph_ids.get(candidate_2).unwrap();
graph.add_edge(*candidate_2_id, *candidate_1_id, (*votecount_1, *votecount_2));
}
}
return graph;
}
fn mapped_candidates(&mut self, selection: &[T]) -> Vec<usize> {
let mut mapped = Vec::<usize>::new();
for selected in selection.iter() {
if self.candidates.contains_key(&selected) {
mapped.push(*self.candidates.get(&selected).unwrap()); } else {
let len = self.candidates.len();
self.candidates.insert(selected.clone(), len);
mapped.push(len);
}
}
return mapped;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn condorcet_test() {
let mut tally = DefaultCondorcetTally::new(2);
tally.add(vec!["Alice", "Bob", "Cir"]);
tally.add(vec!["Alice", "Bob", "Cir"]);
tally.add(vec!["Alice", "Bob", "Cir"]);
let winners = tally.winners();
assert_eq!(winners.into_vec(), vec! {("Alice", 0), ("Bob", 1)});
let mut tally = DefaultCondorcetTally::new(1);
tally.add(vec!["Alice", "Bob", "Cir"]);
tally.add(vec!["Bob", "Cir", "Alice"]);
tally.add(vec!["Cir", "Alice", "Bob"]);
let winners = tally.winners();
assert_eq!(winners.rank(&"Alice").unwrap(), 0);
assert_eq!(winners.rank(&"Bob").unwrap(), 0);
assert_eq!(winners.rank(&"Cir").unwrap(), 0);
}
#[test]
fn condorcet_wikipedia_test() {
let mut tally = DefaultCondorcetTally::new(4);
tally.add_weighted(vec!["Memphis", "Nashville", "Chattanooga", "Knoxville"], 42);
tally.add_weighted(vec!["Nashville", "Chattanooga", "Knoxville", "Memphis"], 26);
tally.add_weighted(vec!["Chattanooga", "Knoxville", "Nashville", "Memphis"], 15);
tally.add_weighted(vec!["Knoxville", "Chattanooga", "Nashville", "Memphis"], 17);
let winners = tally.winners();
assert_eq!(
winners.into_vec(),
vec! {("Nashville", 0), ("Chattanooga", 1), ("Knoxville", 2), ("Memphis", 3)}
);
}
#[test]
fn condorcet_graph_test() {
let mut tally = DefaultCondorcetTally::new(1);
tally.add_weighted(vec!["a", "c", "d", "b"], 8);
tally.add_weighted(vec!["b", "a", "d", "c"], 2);
tally.add_weighted(vec!["c", "d", "b", "a"], 4);
tally.add_weighted(vec!["d", "b", "a", "c"], 4);
tally.add_weighted(vec!["d", "c", "b", "a"], 3);
let graph = tally.build_graph();
assert_eq!(graph.node_count(), 4);
assert_eq!(graph.edge_count(), 6);
for index in graph.node_indices() {
let candidate = *graph.node_weight(index).unwrap();
for edge in graph.edges(index).map(|e| e.weight()) {
match candidate {
"a" => assert!(*edge == (13, 8) || *edge == (11, 10) || *edge == (14, 7)),
"b" => assert!(*edge == (13, 8) || *edge == (15, 6) || *edge == (19, 2)),
"c" => assert!(*edge == (12, 9) || *edge == (15, 6) || *edge == (14, 7)),
"d" => assert!(*edge == (12, 9) || *edge == (11, 10) || *edge == (19, 2)),
_ => panic!("Invalid candidate"),
}
}
}
}
}