I want to rebalancing the data in array to make all element same value. For example
Before:
Array
(
[1] => 2
[2] => 4
[3] => 1
[4] => 2
)
After:
Array
(
[1] => 3
[2] => 2
[3] => 2
[4] => 2
)
Another example
Before:
Array
(
[1] => 2
[2] => 3
[3] => 1
[4] => 2
)
After:
Array
(
[1] => 2
[2] => 2
[3] => 2
[4] => 2
)
With PHP language, anyone have idea how to do that?.
CodePudding user response:
Here is a simple way to do it:
<?php
$a = [2, 4, 1, 2];
$sum = array_sum($a);
$len = count($a);
$r = $sum % $len;
$q = ($sum - $r) / $len;
$res = [];
for($i=0;$i<$len;$i )
$res[] = $i < $r ? $q 1 : $q;
var_dump($res);
?>
CodePudding user response:
A solution making use of PHP features. Note the idiom on the last line.
<?php
$arr = [6,4,9,3,8,2,1,5];
// Calculate the total of the array elements
$sum = array_sum($arr);
$len = count($arr);
// Using integer division and modulo arithmetic calculate the average and remainder
$avg = intdiv($sum,$len);
$rem = $sum % $len;
// Create a result array and fill with the average
$result = array_fill(0,$len,$avg);
// Spread the remainder over the first few elements.
while($rem){$result[--$rem] ;}
var_dump($result);
?>
Example: https://3v4l.org/nY2Fo