Challenge to calculate maximum quantity and split sets with PHP
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;
These are some considerations about finding all combinations:
First find all combinations to achive the larger of the two categories (A or B) by 1 or 2 items; it shall be easy to calculate the possible amounts of 1s and 2s and then to enumerate their positions (combinations I).
10 = 2+2+2+2+2 or 1+1+1+1+1+1+1+1+1+1 or 2+2+2+1+1+1+1
Then you can add the other categorie's amount. Each set of 2 is already full, each set of 1 may or may not get another one attached. Having all such combinations II (2 for each set of 1), you can calculate how many of the smaller category are missing. Eliminate such combinations II that include too many of the second category.
Finally the amount of missing items in each combination II must be filled up - using 0/1 or 0/2 sets. This is the same problem as above. Due to smaller amounts, caching may increase performance here. So for each combination II you enumerate by the combinations for the missing items and finally have the combinations III you were looking for.
Together:
- Possible amounts of 1 (1/0) and 2 (2/0)-sets to achive the larger categorie's (e.g. A's) amount I. Systematic shuffling of the 1/0s and 2/0s II. Two possible combinations for each 1/0 -> 1/0 or 1/1 - and elimination of impossible combinations II III. Possible combinations for the missing amount of (e.g.) B's like in I
However, solving puzzles has not a lot to do with PHP. And regarding performance it depends a lot on the system on the amounts. Caching may increase performance for some combinations and decrease for others. And of course the algorith suggestes above has a lot of room for optimizations.
精彩评论