I have a shopping cart of items and i can ship items if i can get them into cases of 4,6, or 12 evenly with no left overs. I thought i had it figure out however if my cart had 8 items my code failed cause it figure out 1 6 with 2 left over instead of figuring uut it could work in 2 4 packs. 8 of course isnt the only number that can cause what i have to fail but its one example. How can i get my code to figure this out corectly? Below is what i have now and im still ending up with and amount in the $qTY var with 8 as an example of it failing.
$num12s = $tQTY / 12;
$num12s = explode(".", $num12s);
$numCases = $num12s[0];
if($num12s[0] >= 1){
$doSub = $num12s[0] * 12;
$tQTY = $tQTY - $doSub;
}
$num6s = $tQTY / 6;
$num6s = explode(".", $num6s);
$numCases = $numCases + $num6s[0];
if($num6s[0] >= 1){
$doSub = $num6s[0] * 6;
$tQTY = $tQTY - $doSub;
}
$num4s = $tQTY / 4;
$num4s = explode(".", $num4s);
$numCases = $numCases + $num4s[0];
if($num4s[0] >= 1){
$doSub = $num4s[0] * 4;
$tQTY = $tQTY - $doSub;
}
I need to fill a case of 12 first and if i cant do that i need to fill a case of 6 next and if i cant do that i need to fill a case of 4 BUT if i cant do that in that order than 2 cases of 4 (for carts with 8) will do or a case of 12 a case of 6 and a case of 4 (for carts with 22) etc.
isn't this completely unneccessary, assuming you only want to know if it's possible to deliver the items (without information about how the packages will be partitioned)? in that case it's very easy: evey even number >=4 will work, so it's just:
$possible = ($number>=4 && $number%2==0);
EDIT:
if you also need more detailed information about the packaging, i'd create some functions like these (see it working on codepad):
/*
* determines if the given number of items is deliverable or not.
*/
function delivery_possible($number_of_items){
return ($number_of_items>=4 && $number_of_items%2==0);
}
/*
* returns an array containing a counter for each package-size given
* the number of items. returns false if it can't be solved without
* leaving a rest.
*/
function delivery_packages($number_of_items){
if(!delivery_possible($number_of_items)){
return false; //impossibru!!!
}
$r = array('size4'=>0, 'size6'=>0, 'size12'=>0);
$r['size12'] = $number_of_items%12==0?(int)($number_of_items/12):(int)(($number_of_items-4)/12);
$number_of_items -= $r['size12']*12;
$r['size6'] = $number_of_items%6==0?(int)($number_of_items/6):(int)(($number_of_items-4)/6);
$number_of_items -= $r['size6']*6;
$r['size4'] = (int)($number_of_items/4);
return $r;
}