Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created April 6, 2024 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnLBevan/6a5a30ac3e687695b3ea4680277833fc to your computer and use it in GitHub Desktop.
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.
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