<?php $max_weight = 100; // init with some random weights $objects = []; for ($i = 1; $i <= 100; $i++) { $objects[] = (object) ['id' => $i, 'weight' => rand(1, 50)]; } // sort by weight, heaviest first usort($objects, function ($a, $b) { return $b->weight <=> $a->weight; }); $containers = []; $container_number = 0; $total_weight = 0; while (true) { $container_number++; $container = []; $container_weight = 0; foreach ($objects as $key => $object) { // add this object to the container if it won't push it over the max weight if ($container_weight + $object->weight <= $max_weight) { $container[] = $object; unset($objects[$key]); $container_weight += $object->weight; $total_weight += $object->weight; if ($container_weight == $max_weight) { break; } } } $containers[$container_number] = $container; $container_contents = count($container); echo 'Container #' . $container_number . ' total weight: ' . $container_weight . ' (' . $container_contents . ' items)' . PHP_EOL; if (empty($objects)) { break; } } echo 'Total weight: ' . $total_weight . PHP_EOL;
You have javascript disabled. You will not be able to edit any code.