VBA recursive “For loops” Permutation?

后端 未结 3 1277
执念已碎
执念已碎 2021-01-25 09:30

Below is my code. I would like to achieve the same result by recursive method because the number of nested loops is varying from 2 to max 8.

Sub permutation()

         


        
3条回答
  •  面向向阳花
    2021-01-25 10:21

    If you still want the fix to the code to produce the desired outcome.

    Sub RecurseMe(a, v, depth, rw)
    
        If a > depth Then
            rw = rw + 1
            PrintV v, rw
            Exit Sub
        End If
        For x = 1 To 2
            v(a) = x + ((a - 1) * 2)
            a = a + 1
            RecurseMe a, v, depth, rw
            a = a - 1
        Next x
    End Sub
    
    Sub PrintV(v, rw)
        For j = 1 To UBound(v)
            ActiveSheet.Cells(rw, j) = v(j) ' & " ";
        Next j
    End Sub
    Sub test()
        Dim v()
        Dim rw As Long
        rw = 0
        depth = 8 'adjust to adjust the number of columns
        a = 1
        ReDim v(1 To depth)
        RecurseMe a, v, depth, rw
    End Sub
    

提交回复
热议问题