Get all combinations of an array

前端 未结 4 739
时光说笑
时光说笑 2021-01-07 10:24

I\'m currently trying to make a function that gets all possible combinations of array values.

I have come up with a non function version but it\'s limited to 3 value

4条回答
  •  长发绾君心
    2021-01-07 11:07

    I tried to learn something new and help you out but Im stuck. maybe this will help you get in the right direction but I dont know enough about Powershell recursion to figure this out. I converted the php to powershell and in theory it should work but it doesnt.

    $array = @('Alpha', 'Beta', 'Gamma', 'Sigma')
    
    
    function depth_picker([system.collections.arraylist]$arr,$temp_string, $collect)
    {
    if($temp_string -ne ""){$collect += $temp_string}
        for($i = 0; $i -lt $arr.count;$i++)
        {
        [system.collections.arraylist]$arrCopy = $arr
        $elem = $arrCopy[$i]
        $arrCopy.removeRange($i,1)
        if($arrCopy.count -gt 0){
        depth_picker -arr $arrCopy -temp_string "$temp_string $elem" -collect $collect}
        else{$collect += "$temp_string $elem"}
        }
    }
    $collect = @()
    depth_picker -arr $array -temp_string "" -collect $collect
    $collect
    

    It seems to work and will get you the first set of possibles:

    Alpha
    Alpha Beta
    Alpha Beta Gamma
    Alpha Beta Gamma Sigma
    

    But for some reason that I cant figure out when it gets back to the previous functions and does $i++ then checks ($i -lt $arr.count) $arr.count it always 0 so it never goes to the next iteration to continue finding the possibilities.

    Hopefully someone else can fix what I cant seem to figure out as I dont know enough about recursion. But it seems that with each level of depth called the previous depth level $arr variable and values is lost.

提交回复
热议问题