php - Distribute associative array elements into groups with a maximum sum per group
233
I need to split my associative array into bunches of not greater than 50 in each bunch. Multiple elements may be pushed into a given group to ensure that a group reaches 50 before starting a new group.
Sample input:
$array = [
'5' => 142,
'2' => 57,
'18' => 37
];
Desired result:
[
['5' => 50],
['5' => 50],
['5' => 42, '2' => 8],
['2' => 49, '18' => 1],
['18' => 36],
];
Answer
Solution:
just mind games
Answer
Solution:
You could try something like this :
Outputs :
Answer
Solution:
My train of thought for this task aligns with @Syscall's "push & consume" approach.
Code: (Demo)