获取数组的所有组合

时间:2014-08-27 05:57:25

标签: arrays function powershell

我目前正在尝试创建一个能够获得所有可能的数组值组合的函数。

我已经提出了一个非功能版本,但它仅限于3个值,所以我试图通过它来创建一个函数来变得更加Dynamic

我尝试搜索SO但是找不到我试图做的PowerShell示例,我可以找到PHP版本,但我的PHP非常有限

PHP: How to get all possible combinations of 1D array?

非功能脚本

$name = 'First','Middle','Last'

$list = @()

foreach ($c1 in $name) {
    foreach ($c2 in $name) {
        foreach ($c3 in $name) {
            if (($c1 -ne $c2) -and ($c2 -ne $c3) -and ($c3 -ne $c1))
            {
                $list += "$c1 $c2 $c3"
            }
        }
    }
} 

这给了我结果

First Middle Last
First Last Middle
Middle First Last
Middle Last First
Last First Middle
Last Middle First

我不确定当我递归函数时如何重新排列值,这是我到目前为止所做的:

<#
.Synopsis
    Short description
.DESCRIPTION
    Long description
.EXAMPLE
    Example of how to use this cmdlet
.EXAMPLE
    Another example of how to use this cmdlet
#>
function Get-Combinations
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string[]]$Array,

        # Param1 help description
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$false,
                   Position=1)]
        [string]$Temp,

        # Param1 help description
        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
        [string[]]$Return
    )

    Begin
    {
        Write-Verbose "Starting Function Get-Combinations with parameters `n`n$($Array | Out-String)`n$temp`n`n$($Return | Out-String)"

        If ($Temp)
        {
            $Return = $Temp
        }

        $newArray = new-object system.collections.arraylist
    }
    Process
    {
        Write-Verbose ($return | Out-String)

        For($i=0; $i -lt $Array.Length; $i++)
        {
            #Write-Verbose $i

            $Array | ForEach-Object {$newArray.Add($_)}
            $newArray.RemoveAt($i)

            Write-Verbose ($newArray | Out-String)

            if ($newArray.Count -le 1)
            {
                Get-Combinations -Array $newArray -Temp $Temp -Return $Return
            }
            else
            {
                $Return = $Temp
            }
        }
        $newArray
    }
    End
    {
        Write-Verbose "Exiting Function Get-Combinations"
    }
}

$combinations = @("First","First2","Middle","Last")

$Combos = Get-Combinations -Array $combinations

$Combos

但我得到的输出到处都是

First2
Last
First2
Last
First
First2
Middle
Last
First
First2
Middle
Last

28/08更新

越来越近但仍然得到奇怪的输出

<#
.Synopsis
    Short description
.DESCRIPTION
    Long description
.EXAMPLE
    Example of how to use this cmdlet
.EXAMPLE
    Another example of how to use this cmdlet
#>
function Get-Combinations
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                    ValueFromPipelineByPropertyName=$true,
                    Position=0)]
        [string[]]$Array,

        # Param1 help description
        [Parameter(Mandatory=$false,
                    ValueFromPipelineByPropertyName=$false,
                    Position=1)]
        [string]$Temp,

        # Param1 help description
        [Parameter(Mandatory=$false,
                    ValueFromPipelineByPropertyName=$true,
                    Position=2)]
        [string[]]$Return
    )

    Begin
    {
        Write-Verbose "Starting Function Get-Combinations with parameters `n`n$($Array | Out-String)`n$temp`n`n$($Return | Out-String)"

        If ($Temp)
        {
            $Return += $Temp
        }

        #$newArray = new-object [System.Collections.ArrayList]
        #$Array | ForEach-Object {$newArray.Add($_) | Out-Null}

        [System.Collections.ArrayList]$newArray = $Array
    }
    Process
    {
        Write-Verbose "return -> $return"

        For($i=0; $i -lt $Array.Length; $i++)
        {
            Write-Verbose "`$i -> $i"

            $element = $newArray[0]
            $newArray.RemoveAt(0)

            Write-Verbose "`$newArray -> $newArray"
            Write-Verbose "Element -> $element"

            if ($newArray.Count -gt 0)
            {
                Get-Combinations -Array $newArray -Temp (($temp + " " +$element).Trim()) -Return $Return
            }
            else
            {
                $Return = $Temp + " " + $element
            }
        }
        $return
    }
    End
    {
        Write-Verbose "Exiting Function Get-Combinations"
    }
}

$combinations = @("First","First2","Middle","Last")

$return = @()

$Combos = Get-Combinations -Array $combinations -Return $return

$Combos

新输出(是的,在“最后”值之前有一个空格,我不知道为什么)

First First2 Middle Last
First First2 Last
First Middle Last
First Last
First2 Middle Last
First2 Last
Middle Last
 Last

4 个答案:

答案 0 :(得分:3)

这是我的解决方案:

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(", ", $_))
}

编辑:在一个函数中相同(Permute)。这是作弊,但是因为我用lambdas替换了普通函数。您可以使用自己处理的堆栈替换递归调用,但这会使代码变得非常复杂......

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(", ", $_))
}

答案 1 :(得分:2)

我试着学习一些新东西并帮助你,但我陷入困境。也许这会帮助你找到正确的方向,但我不太了解Powershell递归来解决这个问题。我将php转换为powershell,理论上它应该可以工作,但它没有。

$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

它似乎有效,并将为您提供第一组可能:

Alpha
Alpha Beta
Alpha Beta Gamma
Alpha Beta Gamma Sigma

但由于某种原因,我无法弄清楚它何时回到之前的函数并且$ i ++然后检查($ i -lt $ arr.count)$ arr.count它总是为0所以它永远不会进入下一个迭代继续寻找可能性。

希望其他人能解决我似乎无法解决的问题,因为我对递归知之甚少。但似乎每个级别的深度称为前一个深度级别$ arr变量和值都会丢失。

答案 2 :(得分:0)

这是我的解决方案,具有递归功能。它生成空格分隔的字符串,但用$ list [$ i] .split(&#34;&#34;)分割每个元素非常简单:

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

答案 3 :(得分:0)

Micky Balladelli发布的解决方案几乎对我有用。这是一个不重复值的版本:

Function Get-Permutations 
{
    param ($array_in, $current, $depth, $array_out)
    $depth++
    $array_in = $array_in | select -Unique
    for ($i = 0; $i -lt $array_in.Count; $i++)
    {
        $array_out += ($current+" "+$array_in[$i]).Trim()
        if ($depth -lt $array_in.Count)
        {
            $array_out = Get-Permutations $array_in ($current+" "+$array_in[$i]) $depth $array_out
        }
        else {}
    }
    if(!($array_out -contains ($array_in -Join " "))) {}
    for ($i = 0; $i -lt $array_out.Count; $i++)
    {
        $array_out[$i] = (($array_out[$i].Split(" ")) | select -Unique) -Join " "
    }
    $array_out | select -Unique
}