Skip to content

Instantly share code, notes, and snippets.

@andrienko
Created October 10, 2016 01:32
Show Gist options
  • Save andrienko/8c07c87821856cb7ca3b516b24ecc4e0 to your computer and use it in GitHub Desktop.
Save andrienko/8c07c87821856cb7ca3b516b24ecc4e0 to your computer and use it in GitHub Desktop.
PHP 5.2. Calculating percentage using largest remainder method (bit tricky)
<?php
function calculate_percentage($aw,$tp=0,$t=0){
foreach($aw as $a) $t += $a['votes'];
foreach($aw as &$a)$tp += floor($a['percentage'] = $a['votes'] / $t * 100);
uasort($aw, 'sort_by_remainder');
foreach ($aw as &$v) $v['percentage'] = ($tp++ < 100) ? ceil($v['percentage']) : floor($v['percentage']);
ksort($aw);
return $aw;
}
function sort_by_remainder($a, $b){
return $a['percentage']-floor($a['percentage']) < $b['percentage']-floor($b['percentage']);
}
var_dump(calculate_percentage(array(
array('title'=>'Meh1','votes'=>1),
array('title'=>'Meh2','votes'=>2),
array('title'=>'Meh3','votes'=>3),
array('title'=>'Meh4','votes'=>44)
)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment