John Davidson

php - Get all the combinations a number can be split into

0 comments
Message:


I have a fixed number (5) and a fixed length (2):


I want to find all the combinations that can sum 50 (this can vary of course).


For example, for 50, and a length of 2, I want to get:


[[1, 49], [2, 48], [3, 47], [4, 46], ...],


For 50 and a length of 4, I want to get:


[[1, 1, 1, 47], [1, 1, 2, 46], [1, 1, 3, 45], [1, 1, 4, 44], ...],


I have no clue how to do this, or whether there's a name in mathematics for this.


This is what I have (doesn't have to use generators):


function getCombinations(array $numbers, int $sum, int $setLength) : \Generator {
$numbersLowestFirst = $numbers;
asort($numbersLowestFirst);
$lowestNumber = 0;
foreach ($numbersLowestFirst as $number) {
// array might be associative and we want to preserve the keys
$lowestNumber = $number;
break;
}

$remainingAmount = $sum - $lowestNumber;
$remainingNumberofItems = $setLength - 1;

$possibleItemCombinations = array_pad([$remainingAmount], $remainingNumberofItems, $lowestNumber);

}


My Answer:
Here is an updated version of your function that generates all possible combinations of numbers that sum up to a given total, with a fixed length:

php
function getCombinations(int $total, int $length) : \Generator {
$numbers = range(1, $total - 1);

foreach ($numbers as $number) {
if ($length == 1) {
yield [$number];
} else {
foreach (getCombinations($total - $number, $length - 1) as $combination) {
array_unshift($combination, $number);
yield $combination;
}
}
}
}

$total = 50;
$length = 2;

foreach (getCombinations($total, $length) as $combination) {
print_r($combination);
}


This function uses recursion to generate all possible combinations of numbers that sum up to the given total, with the specified length. You can adjust the `$total` and `$length` variables to get combinations for different totals and lengths.

Rate this post

4 of 5 based on 6483 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us