여기서 최대 변수 값은 1, 2이다 루프 중첩의 세트에 대해 간단 추상화 3 :각각
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 중첩 임의의 수를 나타내는 추상화를하려는 for 루프.
NestedForLoops (1, 2, 3) { Param($i, $j, $k) "$i $j $k" }
여기 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
}
예 전화 :
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
이 더 나은 방법이 있나요 그래서 예를 들어, 위의이 같은으로 호출 될 것인가?
이기기위한 메타 프로그래밍! :-) 흥미로운 접근! – dharmatech