The task of calculating the maximum number and splitting sets using PHP

I have two elements: A and B. You can only have one set of 2 items at a time. This leads to the following combinations:

A B
1 0
2 0
0 1
0 2
1 1

If you need 3 or more items, the remaining objects are overflowed into a new set. Sets of 2 are preferred for individual items in a set. Examples:

  • 2 lots A and 1 lot B (3 items total) will be 2 sets: 2 0, 0 1 OR 1 1, 1 0
  • 3 lots A and 4 lots B (a total of 7 positions) will be 4 sets: 2 0, 1 0, 0 2, 0 2 OR 1 1, 1 1, 1 1, 0 1 ...

Which PHP code is most effective for calculating:

  • Combinations in each set
  • Total number of sets
  • All kit options

Example:

//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;
+3
source share
1 answer

:

(A B) 1 2 ; 1s 2s, ( I).

10 = 2 + 2 + 2 + 2 + 2 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 2 + 2 + 2 + 1 + 1 + 1 + 1

. 2 , 1 . II (2 1), , . II, .

, II - 0/1 0/2 . , . - . II , , III, .

:

  • 1 (1/0) 2 (2/0) - (, A) I. 1/0s 2/0s II. 1/0 → 1/0 1/1 - II III. (,) B, I

PHP. . . , , , , .

+1

Source: https://habr.com/ru/post/1753816/


All Articles