7

我想运行这样的东西:

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”值的最佳方法是什么?我应该将它们存储在数组中吗?还是有完全不同的方法来解决这个问题?

4

2 回答 2

0

您可以添加一个数组或类似结构作为参数,Iterate()并为每次调用Iterate()添加当前值i到数组中。

因此,您可以知道循环的深度和“父”循环的当前值。

于 2012-06-20T11:12:34.260 回答
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)
于 2012-06-20T11:59:42.473 回答