Skip to content

Instantly share code, notes, and snippets.

@richardolsson
Created June 17, 2013 08:37
Show Gist options
  • Save richardolsson/5795489 to your computer and use it in GitHub Desktop.
Save richardolsson/5795489 to your computer and use it in GitHub Desktop.
Javascript to calculate seats in the Swedish parliament, The Riksdag, based on total number of votes and the results (percentage of votes) for an arbitrary number of parties.
/**
* Calculate number of seats in the Swedish parliament for an arbitrary number
* of parties, from the total number of votes and each party's result as a
* percentage of the total vote. Return an array containing the parties' respective
* number of seats.
*
* The seats are distributed using a "Modified Sainte-Laguë method" algorithm where
* the first divisor is 1.4.
*
* In short, each party is given a "comparison value" based on the total number
* of votes they received divided by 1.4. In each round, the party with the biggest
* comparison value is awarded a seat and gets a new comparison number based on
* the next divisor in a series where 1.4 is followed by 3, 5, 7, 9, et c with
* increments of 2. This continues until all seats have been distributed.
*/
function calcRiksdagSeats(numVotes, partyResults)
{
var i, partyVotes, partyComps, partyDivs, partySeats, numSeats;
partyVotes = [];
partyComps = [];
partySeats = [];
partyDivs = [];
numSeats = 0;
// Set-up
for (i=0; i<partyResults.length; i++) {
partyVotes[i] = partyResults[i] * numVotes;
partyComps[i] = partyVotes[i] / 1.4;
partySeats[i] = 0;
partyDivs[i] = 3;
// Disqualify tiny parties (<4%)
if (partyResults[i] < 0.04)
partyComps[i] = 0;
}
// Loop over all seats and distribute them according to the
// correct algorithm: For each seat, find the party with the
// biggest comparison value, and award them the seat. Then
// calculate that party's new comparison value by dividing it's
// number of votes by the next divisor, starting at 3 and
// incremented each time by 2.
while (numSeats < 349) {
var maxIdx, maxComp = 0;
// Find maximum comparison value
for (i=0; i<partyComps.length; i++) {
if (partyComps[i] > maxComp) {
maxComp = partyComps[i];
maxIdx = i;
}
}
// Add seat to biggest party after this round
partySeats[maxIdx]++;
numSeats++;
// Prepare for next round by calculating new comparison value
partyComps[maxIdx] = partyVotes[maxIdx] / partyDivs[maxIdx];
partyDivs[maxIdx] += 2;
}
return partySeats;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment