-
Notifications
You must be signed in to change notification settings - Fork 2
/
method-functions.js
78 lines (77 loc) · 2.1 KB
/
method-functions.js
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
module.exports = {
majority: function(votes, options) {
var winner = {name: "no winner", votes: 0};
options.forEach(function(e,i,arr) {
if (e.votes > winner.votes) winner = e;
});
return winner;
},
okay: function(votes, options) {
for (var i = 0; i < options.length; i++) {
options[i].votes = 0;
}
for (var i = 0; i < votes.length; i++) {
for (var j = 0; j < votes[i].length; j++) {
options[votes[i][j]] += 1;
}
}
var winner = {name: "no winner", votes: 0};
options.forEach(function(e,i,arr) {
if (e.votes > winner.votes) winner = e;
});
return winner;
},
av: function(votes, options) {
for (var i = 0; i < votes.length; i++) {
votes[i] = votes[i].vote;
}
for (var i = 0; i < options.length; i++) {
options[i] = options[i].name;
}
if (votes.length === 0) return {name: "no winner", votes: 0};
function tally(votes, options) {
var results = [];
options.forEach(function(e, i, arr) {
results.push(0);
});
votes.forEach(function(e, i, arr) {
results[options.indexOf(e[0])] += 1;
});
results.forEach(function(e, i, arr) {
arr[i] = e/votes.length;
});
return results;
}
function winnerIndex(results) {
if (results.length == 1) return 0;
var index = -1;
results.forEach(function(e, i, arr) {
if (e > 0.5) index = i;
});
return index;
}
function looserIndex(results) {
var min = Infinity;
var index = -1;
results.forEach(function(e, i, arr) {
if (e < min && e > 0) {
min = e;
index = i;
}
});
return index;
}
function dropCanidate(canidate, votes) {
votes.forEach(function(e, i, arr) {
if (e[0] === canidate) arr[i].shift();
});
return votes;
}
do {
var results = tally(votes, options);
var winner = winnerIndex(results);
votes = dropCanidate(options[looserIndex(results)], votes);
} while (winner === -1);
return {name: options[winner], votes: results[winner]};
}
}