So I need a method that will break down an order into the specified sizes. For example:
orderBreakdown(40, [4, 8, 12, 16]);
Would return [16, 16, 8]
(an array of the orders). It needs to have the most efficient breakdown (can't be 12, 12, 12, 4). It also has to be extremely flexible - it can fail (obviously some quantities can't be broken down, for example 39 in that case).
Right now I have:
function quantityBreakdown(int $count, array $units)
{
sort($units);
$units = array_reverse($units); //order units from large to small
$orders = [];
$original_count = $count;
while ($count > 0 && !empty($units))
{
for($i = 0; $i < count($units); $i++)
{
$unit = $units[$i];
while($count >= $unit){
array_push($orders, $unit);
$count = $count - $unit;
}
}
if ($count > 0){
$count = $original_count;
$orders = [];
array_shift($units);
}
}
return $orders;
}
This works in a lot of cases:
quantityBreakdown(19, [6, 8, 11, 17]);
will return [11, 8]
for example. But there are some cases when it will return non-optimal results. quantityBreakdown(36, [6, 8, 11, 17])
will return [6, 6, 6, 6, 6, 6]
, when optimally it should return [17, 11, 8]
. I'm a bit at a loss of where to go from here.