我想运行这样的东西:
For a = 0 To 4
For b = a To 4
For c = b To 4
Console.WriteLine(a & b & c)
Next
Next
Next
但我需要互相创建n个循环。所以我创建了这个方法:
'iFrom = 0; iTo = 4; Depth = 3(loop count);
Private Sub Iterate(ByVal iFrom As Integer, ByVal iTo As Integer, ByVal Depth As Integer)
For i = iFrom To iTo
If Depth - 1 > 0 Then Iterate(iFrom, iTo, Depth - 1)
'Do stuff here
Next
End Sub
从更高级别检索“i”值的最佳方法是什么?我应该将它们存储在阵列中吗?或者有一种完全不同的方法来解决这个问题吗?
答案 0 :(得分:0)
您可以将数组或类似结构作为参数添加到Iterate()
,并且每次调用Iterate()
时,都会将i
的当前值添加到数组中。
因此,您可以知道循环的深度和“父”循环的当前值。
答案 1 :(得分:0)
在玩这种方法后,我终于找到了解决方案。这是:
Private Sub Iterate(ByVal iFrom As Integer, ByVal iTo As Integer, ByVal Depth As Integer, ByVal iValues As Integer())
For i = iFrom To iTo
iValues(Depth - 1) = i
If Depth - 1 > 0 Then
Iterate(i, iTo, Depth - 1, iValues)
Else
'Do stuff, in this case print the current iValues
Console.WriteLine(String.Join("", iValues.Select(Function(x) x.ToString).ToArray))
End If
Next
Console.WriteLine()
End Sub
'Usage:
Dim iValueArray(Depth) As Integer
Iterate(0, 1, 2, iValueArray)