Possible Duplicate:
Generating all Possible Combinations
I’m trying to do a little algorithm in C++ or C#
Basically if you have an array:
{"ab","cd"}
output:
ac
ad
bc
bd
(I have two nested for loops)
but what if i have an array of 3 elements? or 4 ?
Thank you guys 🙂
In order to vary the number of “nested loops” you need to use recursion.
Initial call looks like this:
EDIT (in response to a comment by OP)
To understand what is going on, you need to understand the meaning of the parameters first:
stris the array of strings. Each element of the array corresponds to a nesting level of the imaginary nested loops: element 0 is for the outer loop, element 1 is for the first level of nesting, and so on.partialis the partially constructed result string. It is empty at the initial level, has one character at the first level of nesting, two at the second, and so on.pis the nesting level. It is zero in the initial level, one at the first nesting level, and so on.The function has two parts – the stopping condition, and the body of the recursive call. The stopping condition is simple: once we get to the last level,
partialresult is no longer “partial”: it is complete; we can print it out and exit. How do we know that we’re at the last level? The number of elements ofstrequals the number of levels, so whenpequals the length of thestrarray, we’re done.The body of the recursive call is a loop. It does the same thing that your nested loops do, but for only one level: each iteration adds one letter from its own array, and calls itself recursively for the next level.
The best way to see this in action is to set a breakpoint on the line with the
returnstatement, and look at the call stack window . Click each invocation level, and inspect the values of function parameters.If you are up for an exercise, try modifying this function to take two parameters instead of three. Hint: you can eliminate the last parameter by observing that the length of
partialalways matches the value ofp.