Created
April 6, 2024 07:41
-
-
Save JohnLBevan/6a5a30ac3e687695b3ea4680277833fc to your computer and use it in GitHub Desktop.
Script to produce all combos (including empty) of a set of items. A bit clunky since PS tries to be helpful, but that doesn't play well when returning lists of lists.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-AllCombos { | |
[CmdletBinding()] | |
[OutputType("System.Collections.Generic.List[System.Object]")] | |
Param ( | |
[Parameter(Mandatory)] | |
[AllowEmptyCollection()] | |
#[System.Collections.Generic.List[System.Object]]$arr | |
[System.Collections.Generic.List[System.Object]]$arr | |
) | |
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop | |
write-verbose $arr.Count -Verbose | |
if ($arr.Count -eq 0) { | |
return ,$arr | |
} | |
$lastIndex = $arr.Count-1 | |
$last = $arr[$lastIndex ] | |
$arr.RemoveAt($lastIndex) | |
[System.Collections.Generic.List[[System.Collections.Generic.List[System.Object]]]]$newCombos = Get-AllCombos $arr | |
foreach ($combo in $newCombos) { | |
$newCombo = [System.Collections.Generic.List[System.Object]]::new() | |
$newCombo.Add($last) | |
$newCombo.AddRange($combo) | |
,$combo | |
,$newcombo | |
} | |
} | |
$array = @('a', 'b', 'c', 'd') | |
[System.Collections.Generic.List[[System.Collections.Generic.List[System.Object]]]]$results = Get-AllCombos $array | |
foreach ($x in $results) { | |
$x -join ',' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment