Here's a simple for set of nested for loops where the maximum variable values are 1, 2, and 3 respectively:
for ($i = 0; $i -le 1; $i++)
{
for ($j = 0; $j -le 2; $j++)
{
for ($k = 0; $k -le 3; $k++)
{
"$i $j $k"
}
}
}
I'd like an abstraction for indicating an arbitrary number of nested for loops. So for example, the above would be invoked as something like:
NestedForLoops (1, 2, 3) { Param($i, $j, $k) "$i $j $k" }
Here's one approach based on this answer:
function NestedForLoopsAux([int[]]$max_indices, [int[]]$indices, [int]$index, $func)
{
if ($max_indices.Count -eq 0) { &($func) $indices }
else
{
$rest = $max_indices | Select-Object -Skip 1
for ($indices[$index] = 0; $indices[$index] -le $max_indices[0]; $indices[$index]++)
{ NestedForLoopsAux $rest $indices ($index + 1) $func }
}
}
function NestedForLoops([int[]]$max_indices, $func)
{
NestedForLoopsAux $max_indices (@(0) * $max_indices.Count) 0 $func
}
Example call:
PS C:\> NestedForLoops (1, 2, 3) { Param([int[]]$indices); $i, $j, $k = $indices; "$i $j $k" }
0 0 0
0 0 1
0 0 2
0 0 3
0 1 0
0 1 1
0 1 2
0 1 3
0 2 0
0 2 1
0 2 2
0 2 3
1 0 0
1 0 1
1 0 2
1 0 3
1 1 0
1 1 1
1 1 2
1 1 3
1 2 0
1 2 1
1 2 2
1 2 3
Is there a better way?