我试图找出从一个PowerShell阵列获得独特组合的最佳方式。例如,我的阵列可能是
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 be hoping for an output like this :
B C D E B,C B,D B,E C,D C,E D,E B,C,D C,D,E B,C,D,E我不希望重新安排组合。如果组合C,D已经存在,那么我不想组合D,C。这是多余的,我的目的。
I do not want re-arranged combos. If combo C,D exists already then I do not want combo D,C. It's redundant for my purposes.
我看着这里的功能:得到一个数组的所有组合
I looked into the functions here : Get all combinations of an array
但他们不是我想要的。我一直在努力弄清这一点我自己,但已经花了相当多的时间没有成功。我想我会问这个问题在这里,这样,如果别人已经知道我不会浪费我的时间。
But they aren't what I want. I've been working on figuring this out myself, but have spent quite a bit of time without success. I thought I'd ask the question here so that if someone else already know I'm not wasting my time.
谢谢!
推荐答案这是从C#类的解决方案适应了我的问这个同样的问题。对于任何一组找到所有的子集,包括空集。
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} }使用像这样:
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更多推荐
从PowerShell的阵列独特的连击
发布评论