c++ : dynamic number of nested for loops (without recursion)
I'm writing a code segment that iterates through every permutation of n
digits. So for example, if n = 3, I would want to iterate through each of
the following elements:
0, 0, 0
0, 0, 0
...
0, 1, 0
...
1, 0, 0
...
2, 3, 4
...
9, 9, 9
You get the idea. This is very easy to code using nested for loops:
for(digit1 0 to 9)
for(digit2 0 to 9)
for(digit3 0 to 9)
But I want to generalize this to n digits. If for example n = 10 I now
need 10 nested for loops.
I've thought about this and realized that the problem can be solved using
recursion (depth first search through a tree, with each node having 10
children, 0 to 10, and stopping at depth n). But I'm aiming for high
performance so I don't want to use recursion due to the overhead. What
other alternatives do I have?
No comments:
Post a Comment