phparraysgroupingmathematical-optimizationinteger-arithmetic

Distribute associative array elements into groups with a maximum sum per group


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],
];

Solution

  • just mind games

    $line = [];
    // Invert array
    foreach($arr as $k=>$v) {
       $line = array_merge($line, array_fill(0, $v, $k));
    }
    // Split and count occurrences
    $res = array_map('array_count_values', array_chunk($line, 50));
    print_r($res);
    

    demo