Created
July 8, 2022 13:25
-
-
Save neojoda/fe6f576d99a3b0a3c8add3e52f34fd64 to your computer and use it in GitHub Desktop.
[PHP] Calculate all the possible subsets given an array of elements
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 | |
/** | |
* This is a function run recursevly to calculate all the possible subsets given an array | |
**/ | |
function getAllSubsets($nums, &$result){ | |
for ($i = 0; $i<count($nums); $i++) | |
{ | |
$val = $nums[$i]; | |
$result = ($result == " " ? $result.$val : $result." ".$val); | |
if ($i != 0){ | |
for ($j=0;$j<=$i; $j++) | |
{ | |
$val = $nums[$j]; | |
if ($j==0){ | |
$valInner = $val; | |
} | |
else | |
{ | |
$valInner = $valInner.",".$val; | |
} | |
} | |
$result .= " ".$valInner; | |
} | |
} | |
array_shift($nums); | |
if (count($nums) > 0){ | |
getAllSubsets($nums, $result); | |
} | |
} | |
$result=" "; | |
$nums = ['1','2','3', '4']; | |
getAllSubsets($nums, $result); | |
print_r (explode(" ", $result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment