Get all combinations of an array

前端 未结 4 720
时光说笑
时光说笑 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:04

    Here is my solution with a recursive function. It generates space separated strings but it's quite simple to split each element with $list[$i].split(" "):

    function Get-Permutations 
    {
        param ($array, $cur, $depth, $list)
    
        $depth ++
        for ($i = 0; $i -lt $array.Count; $i++)
        {
            $list += $cur+" "+$array[$i]        
    
            if ($depth -lt $array.Count)
            {
                $list = Get-Permutations $array ($cur+" "+$array[$i]) $depth $list
            }       
        }
    
        $list
    }    
    
    $array = @("first","second","third","fourth")
    $list = @()
    $list = Get-Permutations $array "" 0 $list
    
    $list
    

提交回复
热议问题