Unique Combos from powershell array - No duplicate combos

后端 未结 2 748
梦谈多话
梦谈多话 2021-01-25 06:21

I\'m trying to figure out the best way to get unique combinations from a powershell array. For instance, my array might be

@(B,C,D,E)

I would b

2条回答
  •  执笔经年
    2021-01-25 07:04

    This is an adaptation from a solution for a C# class I took that asked this same question. For any set find all subsets, including the empty set.

    function Get-Subsets ($a){
        #uncomment following to ensure only unique inputs are parsed
        #e.g. 'B','C','D','E','E' would become 'B','C','D','E'
        #$a = $a | Select-Object -Unique
        #create an array to store output
        $l = @()
        #for any set of length n the maximum number of subsets is 2^n
        for ($i = 0; $i -lt [Math]::Pow(2,$a.Length); $i++)
        { 
            #temporary array to hold output
            [string[]]$out = New-Object string[] $a.length
            #iterate through each element
            for ($j = 0; $j -lt $a.Length; $j++)
            { 
                #start at the end of the array take elements, work your way towards the front
                if (($i -band (1 -shl ($a.Length - $j - 1))) -ne 0)
                {
                    #store the subset in a temp array
                    $out[$j] = $a[$j]
                }
            }
            #stick subset into an array
            $l += -join $out
        }
        #group the subsets by length, iterate through them and sort
        $l | Group-Object -Property Length | %{$_.Group | sort}
    }
    

    Use like so:

    PS C:>Get-Subsets @('b','c','d','e')
    
    b
    c
    d
    e
    bc
    bd
    be
    cd
    ce
    de
    bcd
    bce
    bde
    cde
    bcde
    

    Note that computational costs go up exponentially with the length of the input array.

    Elements     SecondstoComplete
    15               46.3488228
    14               13.4836299
    13                3.6316713
    12                1.2542701
    11                0.4472637
    10                0.1942997
     9                0.0867832
    

提交回复
热议问题