Iterating over an indefinitely large number of concentric loops
-
Before I retired, I had to write, or service, programs that simulated behavior of polymer molecules. Each link in the polymer molecule chain could assume up to 3 possible rotation values. Later I wrote this program to do that sort of job:-
#define N 4
int main()
{int i, j, ncases, x[N], start[N], stop[N], n = N; ncases = 0;
for (i = 0; i 0; x[i] = start[i]) for (i--; (++x[i]) <= stop[i]; i = n - 1) { // iterate over all cases
ncases++;
for (j = 0; j < n; j++) putchar('0' + x[j]); // replace by something useful to be done over every allowed combination of values of x[0:N-1]
putchar(' '); }
printf("\n%d cases found\n~~~~~~~~~~~~~~\n", ncases);
printf("press a key to continue:"); i = getchar();
return 0;
}This seems to do the same as:-
for( i[N-1] = start[N-1]; i[N-1] <= stop[N-1]; i[N-1]++ )
for( i[N-2] = start[N-2]; i[N-2] <= stop[N-2]; i[N-2]++ )
for( i[N-3] = start[N-3]; i[N-3] <= stop[N-3]; i[N-3]++ )
for( i[N-4] = ...............................
etc to ..
for( i[1] = start[1]; i[1] <= stop[1]; i[1]++ )
for( i[0] = start[0]; i[0] <= stop[0]; i[0]++ )
{ work to be done for every allowed combination of values of i[0:N-1] }In case this piece of program text is any use to you.
-
Before I retired, I had to write, or service, programs that simulated behavior of polymer molecules. Each link in the polymer molecule chain could assume up to 3 possible rotation values. Later I wrote this program to do that sort of job:-
#define N 4
int main()
{int i, j, ncases, x[N], start[N], stop[N], n = N; ncases = 0;
for (i = 0; i 0; x[i] = start[i]) for (i--; (++x[i]) <= stop[i]; i = n - 1) { // iterate over all cases
ncases++;
for (j = 0; j < n; j++) putchar('0' + x[j]); // replace by something useful to be done over every allowed combination of values of x[0:N-1]
putchar(' '); }
printf("\n%d cases found\n~~~~~~~~~~~~~~\n", ncases);
printf("press a key to continue:"); i = getchar();
return 0;
}This seems to do the same as:-
for( i[N-1] = start[N-1]; i[N-1] <= stop[N-1]; i[N-1]++ )
for( i[N-2] = start[N-2]; i[N-2] <= stop[N-2]; i[N-2]++ )
for( i[N-3] = start[N-3]; i[N-3] <= stop[N-3]; i[N-3]++ )
for( i[N-4] = ...............................
etc to ..
for( i[1] = start[1]; i[1] <= stop[1]; i[1]++ )
for( i[0] = start[0]; i[0] <= stop[0]; i[0]++ )
{ work to be done for every allowed combination of values of i[0:N-1] }In case this piece of program text is any use to you.