[Solved] How to divide items equally in 4 boxes? [closed]


Create a function that gets a product weight and returns a bag number – the one which has the least free space that’s still enough to fit. Put it in the bag. Repeat until done.

$bags = array(60,80,20,10,80,100,90);
$containers = array(1=>100,2=>100,3=>100,4=>100); // number -> free space
$placement = array();

rsort($bags); // biggest first - usually it's better

function bestContainerFor($weight) {
    global $containers;
    $rest = 0;
    $out = 0; // in it won't change $weight fits nowhere
    foreach($containers as $nr=>$space) {
        if($space<$weight) continue; // not enough space
        if($space-$weight<$rest) continue; // we have a better case
        $rest = $space-$weight;
        $out = $nr;
    }
    if($out) $containers[$out]-=$weight; // occupy the space
    return $out;
}

foreach($bags as $nr=>$w) {
    $p = bestContainerFor($w);
    $placement[$nr] = $p; // for later use; in this example it's not needed
    if( $p) print "Bag $nr fits in $p<br>";
    if(!$p) print "Bag $nr fits nowhere<br>";
}

It’s not tested. If you give me some details of your code I’ll try to adapt. This just shows the principle of it.

Note that

  • it works with variable container sizes,
  • it gives you the placement of each bag, not the sum weight,
  • it’s not optimal for equal distribution, just gives a good case

5

solved How to divide items equally in 4 boxes? [closed]