Skip to content

Instantly share code, notes, and snippets.

@rybakit
Created May 26, 2011 10:05
Show Gist options
  • Save rybakit/992872 to your computer and use it in GitHub Desktop.
Save rybakit/992872 to your computer and use it in GitHub Desktop.
Calculate seats distribution according to the D'Hondt method
<?php
/**
* Calculate seats distribution according to the D'Hondt method.
*
* @see http://en.wikipedia.org/wiki/D'Hondt_method
* @author Eugene Leonovich <gen.work@gmail.com>
*
* @param array $polling An associative array (party => votes).
* @param integer $totalSeats The total number of seats to be allocated.
*
* @return array An associative array (party => seats).
*/
function dhondt(array $polling, $totalSeats)
{
$result = array();
$data = array();
foreach ($polling as $party => $votes) {
for ($i = 1; $i <= $totalSeats; $i++) {
$data[0][] = $votes / $i;
$data[1][] = $party;
$data[2][] = $i;
}
$result[$party] = 0;
}
array_multisort($data[0], SORT_DESC, $data[1], SORT_ASC, $data[2]);
for ($i = 0; $i < $totalSeats; $i++) {
$party = $data[1][$i];
$result[$party] = max($result[$party], $data[2][$i]);
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment