I'm working on a shipping module for wine, and was wondering if anyone could give me a hand - basically:
The wine can be shipped in cases of 8, 12 or 15 bottles, each with its own price. The module needs to take the total number of bottles in the order, and work out which combination of cases gives the lowest price. Eg in an order of 31 bottles, the lowest price works out to 1 case of 15 and two cases of 8, (rather than 2 cases of 15 and 1 of 8, or 2 of 12 and one of 8). Currently, I have the following, which almost works, but misses a few possible combinations
foreach ($rates as $case_size => $case_price)
{
$price = floor($total_bottles / $case_size) * $case_price;
$rem = $total_bottles % $case_size;
if($rem > 12)
{
//needs to use another case of 15
$price = $price + $rates[15];
}
elseif($rem > 8)
{
//needs an extra case of 12
$price = $price + $rates[12];
}
elseif($rem > 0)
{
//needs an extra case of 8
$price = $price + $rates[8];
}
$quotes[] = $price;
}
return min($quotes);
From your post your saying that the most price-effective system wouldn't just the one that has uses the lowest cost per bottle of the container, but also needs to be the most efficient at filling the containers. However your algorithm is only looking at would use the fewest large boxes possible. You need an algorithm that will completely fill each case possible.
I would do something like this: Use a recursive program to find the combination that would most completely fill each case.
function fit_case($number, $case_size) {
$rem = $number % $case_size;
$next_size=magic_voodo0();
if($rem==0) { //if perfectly fills it you're done
return ($number/$case_size)*$rates[$case_size];
} else if(($rem % $next_size)/$next_size>.5) {
//if over 50% fills the next case add the next smaller case
return floor($number/$case_size)*$rates[$case_size]+fit_case($rem, $next_size);
} else { //otherwise back off 1 of the biggest cases, and fill the rest
return (floor($number/$case_size)-1)*$rates[$case_size]+fit_case($rem, $next_size);
Hope this helps.