- rsort: documentation ( source)
- array_sum: documentation ( source)
- var_export: documentation ( source)
<?php
$max = 111; //265;
$items = [50, 45, 30, 60, 70, 80];
function nextFitDecreasing(array $items, int $max): array
{
rsort($items);
$result = [];
foreach ($items as $item) {
if (!isset($pallet) || (array_sum($pallet) + $item) > $max) {
unset($pallet);
$result[] = &$pallet;
}
$pallet[] = $item;
}
return $result;
}
function firstFitDecreasing(array $items, int $max): array
{
rsort($items);
$result = [];
foreach ($items as $item) {
foreach ($result as &$pallet) {
if (array_sum($pallet) + $item <= $max) {
$pallet[] = $item;
continue 2;
}
}
$result[] = [$item];
}
return $result;
}
var_export(nextFitDecreasing($items, $max));
echo "\n---\n";
var_export(firstFitDecreasing($items, $max));