Skip to content

Instantly share code, notes, and snippets.

@coopermaruyama
Last active July 20, 2018 22:27
Show Gist options
  • Save coopermaruyama/52f3289473dc0f22f949e8ea20892e0c to your computer and use it in GitHub Desktop.
Save coopermaruyama/52f3289473dc0f22f949e8ea20892e0c to your computer and use it in GitHub Desktop.
Condorcet vote w/ staking
const candidates = [
'A',
'B',
'C',
'D'
]
const votes = [
['B', 'C', 'A', 'D'],
['B', 'C', 'A', 'D'],
['D', 'A', 'C', 'B']
]
const stakes = [
9,
25,
100
]
const winPairs = candidates.reduce((obj, a) => ({
...obj,
[a]: candidates.filter(c => c !== a).reduce((_obj, b) => ({
..._obj,
[b]: 0
}), {})
}), {});
for (var i = 0; i < votes.length; i++) {
const rankings = votes[i];
for (var j = 0; j < rankings.length; j++) {
const a = rankings[j];
for (var k = 0; k < rankings.length; k++) {
const b = rankings[k];
// Don't match a candidate against himself
if (k === j) {
continue;
}
const winner = (j < k) ? a : b;
const loser = (winner === a) ? b : a;
const amountStaked = stakes[i];
const voteValue = Math.sqrt(amountStaked)
winPairs[winner][loser] += voteValue;
}
}
}
const winner = candidates.find(
a => candidates
.filter(c => c !== a) // dont match against self
.every(other => winPairs[a][other] > winPairs[other][a])
)
console.log('winner: ', winner)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment