Last active
August 29, 2015 14:08
-
-
Save gwainor/0d8c049d3680b983f8b1 to your computer and use it in GitHub Desktop.
This function is a recursive iterator function that gets all "unique" combinations with the given items.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function subsetSumRecursive($numbers, $arraySize, $level = 1, $i = 0, $addThis = []) | |
{ | |
if ($level == $arraySize) { | |
$result = []; | |
for (; $i < count($numbers); $i++) { | |
$result[] = array_merge($addThis, array($numbers[$i])); | |
} | |
return $result; | |
} | |
$result = []; | |
$nextLevel = $level + 1; | |
for (; $i < count($numbers); $i++) { | |
$newAdd = array_merge($addThis, array($numbers[$i])); | |
$temp = subsetSumRecursive($numbers, $arraySize, $nextLevel, $i, $newAdd); | |
$result = array_merge($result, $temp); | |
} | |
return $result; | |
} | |
$numbers = [1, 2, 3, 4, 5, 6, 7]; | |
echo "<pre>"; | |
print_r(subsetSumRecursive($numbers, 7)); | |
echo "</pre>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment