I have two items, A and B. You can only have a maximum set of 2 items at any one time. This results in the following combinations:
A B
1 0
2 0
0 1
0 2
1 1
If you want 3 or more items, the remainders spill over into a new set. Sets of 2 are preferred over single items in a set. Examples:
- 2 lots of A and 1 lot of B (total 3 items) would be 2 sets: 2 0, 0 1 OR 1 1, 1 0
- 3 lots of A and 4 lots of B (total 7 items) would be 4 sets: 2 0, 1 0, 0 2, 0 2 OR 1 1, 1 1, 1 1, 0 1...
What PHP code would be most efficient to calculate:
- Combinations in each set
- Total number of sets
- All variations of sets
Sample:
//input
$a = 2;
$b = 1;
$totalItems = $a + $b;
$totalSets = ceil($totalItems/2);
$maxPerSet = 2;
//split into sets of $maxPerSet
for($i = 0; $i < $totalSets; $i ++) {
//calculate combinations of $a and $b
//? code goes here...
if($a >= $maxPerSet){
$setA = $maxPerSet; $setB = 0; $a = $a - $maxPerSet;
} else if($b >= $maxPerSet){
$setB = $maxPerSet; $setA = 0; $b = $b - $maxPerSet;
} else {
if($a + $b > $maxPerSet){
$setA = $a;
$setB = $b - ($a-$maxPerSet); //not right!
$a = 0;
} else {
$setA = $a; $a = 0; $setB = $b; $b = 0;
}
}
//add to array of sets
$sets[$i] = "$setA $setB";
}
//ouput
print_r $sets;