Say I want to exhaust all the possible combinations of 10 variables to find all the solutions to an equation with 10 variables.
I could write out 10 'for' loops, but it would take a lot of space in the code and of course would take a lot of time. Another reason why I want to know this is because it could possible allow me to change the amount of for loops just by changing a number.
I.e., how can I contract the following code into a simple, short form?
1 2 3 4 5 6 7 8 9 10 11 12
for (a[0]=0;a[0]<=9;a[0]++)
for (a[1]=0;a[1]<=9;a[1]++)
for (a[2]=0;a[2]<=9;a[2]++)
for (a[3]=0;a[3]<=9;a[3]++)
for (a[4]=0;a[4]<=9;a[4]++)
for (a[5]=0;a[5]<=9;a[5]++)
for (a[6]=0;a[6]<=9;a[6]++)
for (a[7]=0;a[7]<=9;a[7]++)
for (a[8]=0;a[8]<=9;a[8]++)
for (a[9]=0;a[9]<=9;a[9]++)
if (...)
cout << ... << endl;
NoXzema. Seemingly your code would check one array element at a time. The loop would go like: 'put i=0. Check all a[0] from 0 to 9. Now put i=1. Check all a[1] from 0 to 9, etc.'
What I want the code to do is to check all 10 array elements at a time. As I said, imagine a 10 variable equation with the variables a[0],..,a[9]. I want to search for a combination of the 10 variables that would give me a solution to the equation.
#include <iostream>
template < int N >
void print_it( int (&a)[N], int from_pos = 0 )
{
if( from_pos == N )
{
for( int v : a ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
else
{
for( int i = 0 ; i < N ; ++i )
{
a[from_pos] = i ;
print_it( a, from_pos+1 ) ;
}
}
}
int main()
{
int array[3] {} ;
print_it(array) ;
}
The example by JLBorges shows that lines 8-9 see the array 'a' to have specific enumeration of values on each iteration. Your code would thus be there.