So im try to accomplish is split items evenly through groups with a max on each group, so far I have this funtion, basicly the array count is the number of GROUPS it needs to split the ITEMS and the array values are the max value for each group:
public static function splitItems($groups, $items){
$n = count($groups);
$res = array_fill(0, $n, 0);
while($items >= $groups[0]){
for($i=$n-1;$i>=0;$i--){
if($items >= $groups[$i])
{
$res[$i]++;
$items -= $groups[$i];
}
}
}
if($items > 0){
$res[0]++;
}
return $res;
}
When I run the function like this splitItems([5,5],10);
the result is correct:
Array
(
[0] => 5
[1] => 5
)
Now the only missing part is to take in account the VALUE of array as max value, what i’m looking for are this results:
Input:
splitItems([14,2],10);
splitItems([6,8,2],14);
Output:
Array
(
[0] => 8
[1] => 2
)
Array
(
[0] => 6
[1] => 6
[2] => 2
)
2
Answers
This should work:
Outputs:
Key points:
while
loop is doing. (What it doesn’t do is tell you how many items couldn’t be put into a group – but you could alter that if you wanted to.)Live demo: https://3v4l.org/R8BOg
asort()
to order your elements ascending and preserve the original indexes.This effectively fills the smaller capacities before larger capacities and never overfills. Demo
Output: