An interesting question is: how can one generate large numbers of loops efficiently.
Here we need a huge vast near endless number of loops.
If read a bit about the Busy Beaver numbers, and was pondering:
what if we want to create a really "Busy" C program, that performs an incredibly large number of loops.
HOW DO YOU GENERATE MANY LOOP, WITH LITTLE CODE?
Here's my take:
//note: this is NOT the solution to printing 100^^14, or looping x13 times.
#include <stdio.h>
typedef unsigned u_t;
u_t count;
u_t marker;
void it(u_t n, u_t n2, u_t n3)
{
if (n3 > 0) {
it(n, n2, n3-1); it(n, n2, n3-1);
} else if (n2 > 0) {
it(n, n2-1, marker); it(n, n2-1, marker);
} else if (n > 0) {
it(n-1, marker, marker); it(n-1, marker, marker);
} else
count++;
}
int main(void)
{
u_t i;
for (i = 0; i < 6; ++i) {
it(marker = i, i, i);
printf("%2u %u\n", i, count);
count = 0;
}
return 0;
}
One can of course generalize the number of arguments, by using an array and dynamic memory:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned u_t;
u_t count;
void *create_copy(u_t num, const u_t *p)
{
void *tmp = malloc(num*sizeof(u_t));
if (tmp == NULL) {
fprintf(stderr, "Error: Out of memory\n");
exit(EXIT_FAILURE);
}
memcpy(tmp, p, num*sizeof(p[0]));
return tmp;
}
u_t marker;
void dec(u_t num, u_t *copy, u_t offset)
{
u_t *lim = copy+num;
copy += offset;
(*copy)--;
while ((++copy) < lim)
*copy = marker;
}
void print_current(u_t num, const u_t *p)
{
const u_t *lim = p+num;
while (p < lim) {
printf("%u ", *p);
++p;
}
putchar('\n');
}
void it(u_t num, u_t *p)
{
u_t *p2 = p+num;
u_t *copy;
u_t n;
//print_current(num, p);
while (p2 > p) {
n = *(--p2);
if (n > 0) {
copy = create_copy(num, p);
dec(num, copy, p2-p);
it(num, copy); it(num, copy);
free(copy);
return;
}
}
count++;
}
int main(void)
{
u_t i;
for (i = 0; i < 3; ++i) {
marker = i;
it(3, (u_t []){i, i, i});
printf("%2u %u\n", i, count);
count = 0;
}
return EXIT_SUCCESS;
}
Can you come up with some code that creates even more loops, than running say:
it(5, (u_t []){(u_t)-1, (u_t)-1, (u_t)-1, (u_t)-1, (u_t)-1};
??
Here one will create insanely many loops, but I think the stack will suffer!!
So:
HOW DO YOU GENERATE MANY LOOP, WITH LITTLE CODE AND WITHOUT "ABUSING" THE STACK?
How can one create insanely many loops, without abusing the stack? (Is there an elegant way, that perhaps does not use recursion?)