Created
December 6, 2020 10:56
-
-
Save AlexRogalskiy/bbb705058fb85bc47171f2ec59c22404 to your computer and use it in GitHub Desktop.
Cartesian product (Powershell)
This file contains hidden or 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 CartesianProduct { | |
param | |
( | |
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
[Hashtable] | |
$values = @{ Foo = 1..5; Bar = 1..10} | |
) | |
$keys = @($values.GetEnumerator() | ForEach-Object { $_.Name }) | |
$result = @($values[$keys[0]] | ForEach-Object { @{ $keys[0] = $_ } }) | |
if ($keys.Length -gt 1) { | |
foreach ($key in $keys[1..($keys.Length - 1)]) { | |
$result = foreach ($entry in $result) { | |
foreach ($value in $values[$key]) { | |
$entry + @{ $key = $value } | |
} | |
} | |
} | |
} | |
$result | |
} | |
foreach ($entry in CartesianProduct @{ Foo = 0..3; Bar = ("a", "b") }) { | |
Write-Host "Foo = $($entry.Foo) Bar = $($entry.Bar)" | |
} | |
<# | |
Foo = 0 Bar = a | |
Foo = 1 Bar = a | |
Foo = 2 Bar = a | |
Foo = 3 Bar = a | |
Foo = 0 Bar = b | |
Foo = 1 Bar = b | |
Foo = 2 Bar = b | |
Foo = 3 Bar = b | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment