Created
October 10, 2016 01:32
-
-
Save andrienko/8c07c87821856cb7ca3b516b24ecc4e0 to your computer and use it in GitHub Desktop.
PHP 5.2. Calculating percentage using largest remainder method (bit tricky)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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