Get all combinations of an array

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

    Here is my solution:

    function Remove ($element, $list)
    {
        $newList = @()
        $list | % { if ($_ -ne $element) { $newList += $_} }
    
        return $newList
    }
    
    
    function Append ($head, $tail)
    {
        if ($tail.Count -eq 0)
            { return ,$head }
    
        $result =  @()
    
        $tail | %{
            $newList = ,$head
            $_ | %{ $newList += $_ }
            $result += ,$newList
        }
    
        return $result
    }
    
    
    function Permute ($list)
    {
        if ($list.Count -eq 0)
            { return @() }
    
        $list | %{
            $permutations = Permute (Remove $_ $list)
            return Append $_ $permutations
        }
    }
    
    cls
    
    $list = "x", "y", "z", "t", "v"
    
    $permutations = Permute $list
    
    
    $permutations | %{
        Write-Host ([string]::Join(", ", $_))
    }
    

    EDIT: the same in one function (Permute). This is cheating a bit, however since I replaced plain functions whith lambdas. You could replace recursive calls with a stack you handle yourself, but that would make the code unecessarily complex ...

    function Permute ($list)
    {
        $global:remove = { 
            param ($element, $list) 
    
            $newList = @() 
            $list | % { if ($_ -ne $element) { $newList += $_} }  
    
            return $newList 
        }
    
        $global:append = {
            param ($head, $tail)
    
            if ($tail.Count -eq 0)
                { return ,$head }
    
            $result =  @()
    
            $tail | %{
                $newList = ,$head
                $_ | %{ $newList += $_ }
                $result += ,$newList
            }
    
            return $result
        }
    
        if ($list.Count -eq 0)
            { return @() }
    
        $list | %{
            $permutations = Permute ($remove.Invoke($_, $list))
            return $append.Invoke($_, $permutations)
        }
    }
    
    cls
    
    $list = "x", "y", "z", "t"
    
    $permutations = Permute $list
    
    $permutations | %{
        Write-Host ([string]::Join(", ", $_))
    }
    

提交回复
热议问题