I’m developing a function that determines if a list of items fits inside a box using the bin packing algorithm, which places the larger items first and then checks if the others fit in the remaining space (above and to the side).
Here’s my current code:
function fillBox(&$items, &$box, &$savedItems)
{
foreach ($items as $key => $item) {
$bin = $box;
if ($item['width'] <= $box['width'] && $item['long'] <= $box['long'] && $item['height'] <= $box['height']) {
// Change available box space
$box['long'] -= $item['long'];
// Modify bin
$bin['long'] = $item['long'];
$bin['width'] -= $item['width'];
// Store items
$savedItems[] = $item;
// Remove item from array
unset($items[$key]);
// Start iterating through the bin
fillBox($items, $bin, $savedItems);
}
}
$result = empty($items) ? null : $items;
$result = [$savedItems, $result];
return $result;
}
The function works, but sometimes it duplicates some data and I can’t figure out why.
i test with a lot of products, and sometimes it works fine, but i dont’ know why sometimes it doesnt. i want to improve my code so it can return the right answer to any list of items.
Bruno Torres is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.