Search code examples
phparraysgroupingbin-packing

"Bin packing problem": Split a flat array to creates sets of values satisfying a predefined sum


$a = array(8, 16, 16, 32, 8, 8, 4, 4);

With an array like the one above is there a way so I can divide/split the array based on the value suming up to a set value. e.g if I wanted them to equal 32. My final array will have upto 100 values all being either 32, 16, 8 or 4 and I just need to group the items so the value always equal a set amount so in this example its 32.

From the above array I would would hope to get:

$a[0][1] = 16
$a[0][2] = 16

$a[1][3] = 32

$a[2][0] = 8
$a[2][4] = 8
$a[2][5] = 8
$a[2][6] = 4
$a[2][7] = 4

as $a[0] sums up to 32 and so does $a[1] and $a[2].


Solution

  • $a = array(8, 16, 16, 32, 8, 8, 4, 4);
    $limit = 32;
    rsort($a);
    $b = array(array());
    $index = 0;
    foreach ($a as $i) {
        if ($i + array_sum($b[$index]) > $limit) {
            $b[++$index] = array();
        }
        $b[$index][] = $i;
    }
    $a = $b;
    print_r($a);
    

    It will work, but only because in your case you have 4 | 8 | 16 | 32, and only if the needed sum is a multiple of the biggest number (32).