Skip to content

Instantly share code, notes, and snippets.

@geeksunny
Created October 19, 2012 07:20
Show Gist options
  • Save geeksunny/3916703 to your computer and use it in GitHub Desktop.
Save geeksunny/3916703 to your computer and use it in GitHub Desktop.
A simple PHP class to evenly distribute an integer across a set of multiple integer values.
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', '1');
$dv = new divide_num(101);
$arr = array(111, 222, 333);
var_dump($arr);
foreach ($arr as $key=>$ar) {
$dv->add_target($arr[$key]);
}
$dv->distribute_evenly();
//$dv->distribute_proportionately();
var_dump($arr);
unset($dv);
var_dump($arr);
class divide_num {
private $num;
private $targets = array();
public function __construct($num) {
$this->num = $num;
}
public function add_target(&$target) {
$this->targets[] = &$target;
}
public function distribute_evenly($num = false) {
if (!$num) {
$num = &$this->num;
}
$major = (int)($num / count($this->targets));
$minor = (int)($num % count($this->targets));
foreach ($this->targets as $key=>$target) {
$this->targets[$key] += $major;
if ($minor >= 1) {
$this->targets[$key] += 1;
$minor--;
}
}
}
public function distribute_proportionately() {
$sum = array_sum($this->targets);
$num_less = $this->num;
foreach ($this->targets as $key=>$target) {
$portion = (int)($this->num * ($target / $sum));
$this->targets[$key] += $portion;
$num_less -= $portion;
}
$this->distribute_evenly($num_less);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment