-
Notifications
You must be signed in to change notification settings - Fork 0
/
ranked-choice-vote.php
443 lines (409 loc) · 14.6 KB
/
ranked-choice-vote.php
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php
/* Ranked Choice Voting by Seamus Campbell (seamus@seamuscampbell.nyc) with assistance from ChatGPT */
class RankedChoiceVote {
/*
Algorithm methodology:
Put all candidates into a 2-dimensional array with the first dimension being the individual ballot and the second dimension being the order
After each round, see who has the most votes at the front of their rankings
If a candidate passes the win number (simple majority), remove them from contention
If the number of spots for winning candidates is full, stop
Otherwise, order the rankings and find the candidate with the fewest number of votes BUT if there is a "protected candidate" (e.g. "No Endorsement"), find the candidate with the second-fewest votes
Remove the found candidate from all of the ballots (i.e. every candidate goes up one rank)
Continue the process until the number of winners or number of remaining candidates equals the number of maximum winners
*/
private $votes = array(); // input multidimensional array of all of the votes (2-dimensional array)
private $protected_candidate; // if there is a candidate that must be saved round to round, this is where to save it (string)
private $rounds = 1; // counter for number of rounds it has taken to run (int)
private $electionName; // name of office being sought (string)
private $numofWinners; // number of people that can be elected (int)
private $winnerExists = false; // boolean for if a winner has been found (bool)
private $winnerName = []; // array storing the name(s) of the winner(s) (1-dimensional array)
private $numOfSpotsToFill; // number of remaining spots (int)
// constructor function
// return: void
// arguments: array (2 dimensional), string, string, int
public function __construct($votes, $protected_candidate, $electionName, $numofWinners){
$this->votes = $votes; // input array of the votes
$this->protected_candidate = $protected_candidate; // candidate that cannot be eliminated between rounds
$this->electionName = $electionName; // name of the office being sought
$this->numofWinners = $numofWinners; // number of people who can win
$this->numOfSpotsToFill = $numofWinners; // number of spots left to fill
}
// function for telling if there is a winner
// return: bool
// arguments: none
public function getWinnerExists(){
return $this->winnerExists;
}
// function to get the office being sought
// return: string
// arguments: none
public function getElectionName(){
return $this->electionName;
}
// function to get the number of winners
// return: int
// arguments: none
public function getNumOfWinners(){
return $this->numofWinners;
}
// function for outputting winner list
// return: array
// arguments: none
public function getWinner(){
return $this->winnerName;
}
// function to output number of winners in the list
// return: int
// arguments: none
public function getNumberOfConfirmedWinners(){
return sizeof($this->getWinner());
}
// function for outputting list of all of the candidates
// return: array
// arguments: array
public function getCandidateList($array){
$uniqueValues = array();
foreach ($array as $value) {
if (is_array($value)) {
// If the element is an array, recursively call the function
$uniqueValues = array_merge($uniqueValues, getCandidateList($value));
} elseif (!in_array($value, $uniqueValues)) {
// If the element is not already in the unique values array, add it
$uniqueValues[] = $value;
}
}
return $uniqueValues;
}
// functtion to remove spoiled ballots
// return: void
// arguments: array
private function removeBlankArrays($array) {
$tempArray = array_filter($array, function($subArray) {
return !empty($subArray);
});
$this->votes = $tempArray;
}
// function for number of pople whp voted
// return: int
// arguments: none
private function getNumofBallots(){
return count($this->votes);
}
// function to help determine win number
// return: bool
// arguments: int
private function isEven($number){
if($number % 2 == 0){
return true;
}
else{
return false;
}
}
// function for getting the win number (simple majority)
// return: int
// arguments: none
public function getWinNumber(){
$numOfBallots = $this->getNumofBallots();
$winNumber = 0;
if($this->isEven($numOfBallots)){
$winNumber = $numOfBallots/2;
$winNumber++;
}
else{
$numOfBallots++;
$winNumber = $numOfBallots/2;
}
return $winNumber;
}
// function to search through the first item in each ballot (ballot = 1st dimension of the array) and find the person who got the fewest votes
// return: string
// arguments: array (2 dimensional), string
private function getCandidateWithFewest($array, $skip){
$votecount = array();
$firstColumn = $this->getFirstItemInEachDimension($array);
foreach ($firstColumn as $candidate) {
if(!array_key_exists($candidate,$votecount))
{
$votecount[$candidate] = 1;
}
else{
$votecount[$candidate]++;
}
}
asort($votecount);
echo $this->printTally($votecount);
$votecount = array_reverse($votecount);
$fewest = array_key_last($votecount);
if($fewest == $skip){ // if candidate cannot be removed, get next lowest
$fewest = $this->getKeyOfSecondToLastItem($votecount);
}
return $fewest;
}
// function to search through the first item in each ballot (ballot = 1st dimension of the array) and find the person who got the most votes
// return: string
// arguments: array (2 dimensional)
private function getCandidateWithMost($array){
$votecount = array();
$firstColumn = $this->getFirstItemInEachDimension($array);
foreach ($firstColumn as $candidate) {
if(!array_key_exists($candidate,$votecount))
{
$votecount[$candidate] = 1;
}
else{
$votecount[$candidate]++;
}
}
asort($votecount);
$votecount = array_reverse($votecount);
$most = array_key_first($votecount);
return $most;
}
// function to see if there are two candidates running in this round
// return: int
// arguments: array (2 dimensional)
private function getNumOfCandidatesInRound($array){
$votecount = array();
$firstColumn = $this->getFirstItemInEachDimension($array);
foreach ($firstColumn as $candidate) {
if(!array_key_exists($candidate,$votecount))
{
$votecount[$candidate] = 1;
}
else{
$votecount[$candidate]++;
}
}
$numOfCandidates = sizeof($votecount);
return $numOfCandidates;
}
// if there is a candidate that cannot be removed, get the candidate with the second fewest number of votes
// return: string
// arguments: array (1 dimensional)
private function getKeyOfSecondToLastItem($array) {
$keys = array_keys($array);
if (count($keys) >= 2) {
$secondToLastKey = $keys[count($keys) - 2];
return $secondToLastKey;
} else {
return null; // Return null if there are fewer than two elements in the array.
}
}
// function for seeing how many votes each person got in that round
// return: void
// arguments: array (1 dimensional)
private function printTally($array){
$array = array_reverse($array);
foreach($array as $key => $value) {
echo $key . ": " . $value . " votes<br />\r\n";
}
}
// function to remove the person from the entire array
// return: void
// arguments: array (2 dimensional), string
private function removeCandidate(&$array, $search) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
$this->removeCandidate($value, $search);
} elseif (is_string($value) && strpos($value, $search) !== false) {
unset($array[$key]);
}
}
$array = array_values($array);
}
// function for getting the first item in the first dimension of each element the array (i.e. the list of candidates from that round)
// return: array (1 dimensional)
// arguments: array (2 dimensional)
private function getFirstItemInEachDimension($array) {
$firstItems = array();
foreach ($array as $subArray) {
if (is_array($subArray) && count($subArray) > 0) {
$firstItems[] = reset($subArray);
}
}
return $firstItems;
}
// function for adding a winner to the winner array
// return: void
// arguments: string
private function addWinner($winner){
$this->winnerName[] = $winner;
}
// function to get the list of candidates left (basically the same as getCandidateList() but private)
// return: array
// arguments: none
private function findUniqueVotesLeft(){
$flattenedArray = array_reduce($this->votes, 'array_merge', []);
$uniqueItems = array_unique($flattenedArray);
$uniqueItems = array_values($uniqueItems);
return $uniqueItems;
}
// function to get number of candidates left in the race
// return: int
// arguments: none
private function findNumOfUniqueVotesLeft() {
$uniqueItems = $this->findUniqueVotesLeft();
$arrayLen = sizeof($uniqueItems);
return $arrayLen;
}
// function to recalculate win number to account for spoiled ballots
// return: void
// arguments: none
private function recountWinNum(){
}
// function to get the number of spots left
// return: int
// arguments: none
private function getNumberOfSpotsToFill(){
return $this->numOfSpotsToFill;
}
// function to reduce number of spots left by 1
// return: void
// arguments: none
private function reduceNumberOfRemainingSpotsByOne(){
$this->numOfSpotsToFill--;
}
// function for if we are in the last round before figuring out who won
// return: string
// arguments: array (2 dimensional)
private function finalCandidatesRound($array){
$votecount = array();
$firstColumn = $this->getFirstItemInEachDimension($array);
foreach ($firstColumn as $candidate) {
if(!array_key_exists($candidate,$votecount))
{
$votecount[$candidate] = 1;
}
else{
$votecount[$candidate]++;
}
}
asort($votecount);
$votecount = array_reverse($votecount);
foreach ($votecount as $key => $value) {
echo $key . ": " . $value . " votes<br />\r\n";
}
$fewest = array_key_last($votecount);
return $fewest;
}
// function for determining who got the fewest votes and removing them from all ballots; if only two are competing in the round, remove the lowest
// return: void
// arguments: none
private function conductRound(){
if($this->getNumOfCandidatesInRound($this->votes) == 2){
$candidateToRemove = $this->getCandidateWithFewest($this->votes,"Name of a candidate that does not exist");
$candidateThatWonRound = $this->getCandidateWithMost($this->votes);
$this->addWinner($candidateThatWonRound);
$this->reduceNumberOfRemainingSpotsByOne();
echo $candidateToRemove . " was eliminated<br />\r\n";
echo $candidateThatWonRound . " won round<br />\r\n\r\n";
}
else{
$candidateToRemove = $this->getCandidateWithFewest($this->votes,$this->protected_candidate);
echo $candidateToRemove . " was eliminated<br />\r\n\r\n";
}
$this->removeCandidate($this->votes, $candidateToRemove);
}
// function to increment the number of rounds
// return: void
// arguments: none
private function increaseRound(){
$this->rounds++;
}
// function for getting number of candidates that have yet to be eliminated
// return: int
// arguments: none
private function numOfCandidatesLeft(){
$candidateList = $this->findUniqueVotesLeft();
return sizeof($candidateList);
}
// function to see if the top vote-getter is over the threshhold of votes; if so, remove from the list
// return: array
// arguments: array (2 dimensional)
private function seeIfTopVoteGetterIsOverWinNum($array){
$returnArray = array();
$votecount = array();
$firstColumn = $this->getFirstItemInEachDimension($array);
foreach ($firstColumn as $candidate) {
if(!array_key_exists($candidate,$votecount))
{
$votecount[$candidate] = 1;
}
else{
$votecount[$candidate]++;
}
}
asort($votecount);
$votecount = array_reverse($votecount);
$voteCountOutput = "";
foreach ($votecount as $key => $value) {
$voteCountOutput .= $key . ": " . $value . " votes<br />\r\n";
if($value >= $this->getWinNumber())
{
array_push($returnArray,$key);
}
}
if(sizeof($returnArray)>0){
echo $voteCountOutput;
}
return $returnArray;
}
// function for conducting the election
// return: void
// arguments: none
public function conductElection(){
echo "<h2>" . $this->electionName . "</h2>\r\n";
echo "<h2>Number of winners: " . $this->getNumOfWinners() . "</h2>\r\n";
echo "<h2>Win Number: " . $this->getWinNumber() . "</h2>\r\n\r\n";
while($this->getNumberOfSpotsToFill()>0)
{
echo "<h3>Round ". $this->rounds."</h3>\r\n";
echo "Number of candidates left: " . $this->findNumOfUniqueVotesLeft() . "<br />\r\n";
$candidateOverThreshold = $this->seeIfTopVoteGetterIsOverWinNum($this->votes);
// if candidate is over the win number, remove from the list
if(sizeof($candidateOverThreshold)>0){
for($i=0; $i<sizeof($candidateOverThreshold);$i++){
$this->addWinner($candidateOverThreshold[$i]);
$this->removeCandidate($this->votes,$candidateOverThreshold[$i]);
$this->reduceNumberOfRemainingSpotsByOne();
echo $candidateOverThreshold[$i] . " has passed the threshhold of ". $this->getWinNumber() . " votes and will be removed from contention<br />\r\n";
echo "Spots remaining: " . $this->getNumberOfSpotsToFill() . "<br />\r\n\r\n";
}
}
// if we're down to the final candidates, find the one with the higher of the two
elseif($this->numOfCandidatesLeft()-1 == $this->getNumberOfSpotsToFill()){
$winner = $this->finalCandidatesRound($this->votes);
$this->addWinner($winner);
$this->removeCandidate($this->votes,$winner);
$this->reduceNumberOfRemainingSpotsByOne();
echo $winner . " wins last round and is a winner<br />\r\n";
}
else{
$this->conductRound();
}
$this->removeBlankArrays($this->votes);
$this->increaseRound();
}
if($this->getNumberOfSpotsToFill() == 0){
$this->winnerExists = true;
$winnerList = $this->getWinner();
if(sizeof($winnerList)==1){
echo "<p><strong>". $winnerList[0] . " is elected as ". $this->getElectionName() ."</strong></p>";
}
else{
echo "<p><strong>";
for($x = 0; $x < sizeof($winnerList); $x++){
if($x == sizeof($winnerList)-1){
echo $winnerList[$x];
}
else{
echo $winnerList[$x] . ", ";
}
}
echo " are elected as ". $this->getElectionName() ."</strong></p>";
}
}
}
}