How to convert multi-loops to recursion
I want to convert this multi-loop to recursion. I understand recursion, but I don't know how to write it.
'Number of loops : A, B, C, ..., (N)
For iA = 0 To Rest
Ax = A + iA
For iB = iA To Rest
Bx = B + iB
For iC = iB To Rest
Cx = C + iC
List.add ({Ax, Bx, Cx})
Next
Next
Next
So, I hope that the expected results is as below...
when, A=10, B=20, C=30, Rest=3
Ideal values are as below.
Ax, Bx, Cx
{10, 20, 30}, {10, 20, 31}, {10, 20, 32}, {10, 20, 33},
{10, 21, 31}, {10, 21, 32}, {10, 21, 33},
{10, 22, 32}, {10, 22, 33},
{10, 23, 33},
{11, 21, 31}, {11, 21, 32}, {11, 21, 33},
{11, 22, 32}, {11, 22, 33},
{11, 23, 33},
{12, 22, 32}, {12,开发者_如何学编程 22, 33},
{12, 23, 33},
{13, 23, 33}
Total count = 20
Help me please...
I'm not quite sure exactly what language this is, but I think I can provide a complete answer anyway. Here's a general approach for turning a loop into recursion:
Suppose you have a loop
For i = A to B
myfunc(i)
Next
You can instead write the function
recursive_function(int starting_value)
{
myfunc(starting_value)
If(starting_value != A)
return recursive_function(starting_value - 1);
else
return
}
and then instead of running the loop, you call recursive_function(B). This way the recursive function calls myfunc(B), myfunc(B-1), ... , myfunc(A).
You can easily adapt this approach to your situation in one of two ways. The first is to write several recursive functions exactly like I have, and replace your nested loops by nested recursive calls. A potentially easier approach is for your recursive function to take parameters A,B,C and use those to do the next iteration. Actually doing it should be very instructional and you should do it on your own.
Assuming VB:
Function RecursiveAdd(List, Rest, A, B, C, iA, iB, iC)
List.Add({A+iA, B+iB, C+iC})
if iC < Rest then RecursiveAdd(List, Rest, A, B, C, iA, iB, iC+1)
if iB < Rest then RecursiveAdd(List, Rest, A, B, C, iA, iB+1, 0)
if iA < Rest then RecursiveAdd(List, Rest, A, B, C, iA+1, 0, 0)
End Function
This can be simplified if List
, Rest
, A
, B
, and C
are members of the same class as RecursiveAdd
.
精彩评论