Search code examples
c++recursionnested-loopscartesian-product

Generating all the values of N nested for loops


I would like to write a function to do the following, given two arguments to the function int K and int nest_level generate all possible points that result from creating nest_level nested loops where each loop ranges from -K to K. For example if k = 5 and nest_level = 3 the function prints the sequences of numbers that result from the following:

for(int i = -k; i <= k; ++i)
    for(int j = -k; j <= k; ++j)
        for(int m = -k; m <= k; ++m)
            print(i, j, k)

This should work for any K and nest_level

From my research, I understand this should be a recursive solution but i'm having difficulty implementing it specifically in C++.


Solution

  • Use a std::vector. Pass it by reference. In a loop of i from -k to k:

    • push i into it.

    • If length of vector equals nest level, print.

    • Otherwise, recurse, passing in the vector by reference.

    • Now, pop the last element off the end of the vector, and continue the loop.