Generate all tuples with C - better way than nested loops?

c, loops, nested-loops

Solution

Here is pseudocode (not necessarily syntactically-correct C code) for a non-recursive approach to iterate over all possible tuples:

const int vals[]        = { val1, val2, val3, ... };

int       x[NUM_DIMS]   = { vals[0], vals[0], ... };  // The current tuple
int       i[NUM_DIMS]   = { 0 };                      // Index of each element in x[]


while (1)
{
    f(x);  // Whatever

    // Update x (we increment i[] treated as a base-N number)
    int j;
    for (j = 0; j < NUM_DIMS; j++)
    {
        i[j]++;                          // Increment the current digit
        x[j] = vals[i[j]];               // Update (via mapping)
        if (i[j] < NUM_VALS) { break; }  // Has this digit wrapped?
        // We've caused a carry to the next digit position
        i[j] = 0;                        // Wrap
        x[j] = vals[0];                  // Update (via mapping)
    }
    if (j == NUM_DIMS) { break; }  // All digits wrapped, therefore game over
}

Problem

I have an array `double x[]` of length 11 and a function `f(double x[])`. I want to find the minimum of the function `f()` by discretization. So for given values `val1, val2, ..., valn` I need a loop trough all the tuples of x in {val_1, ..., val_n}^11. I could easily use 11 nested loops, but is this really the most efficient I could do? Edit: To clarify things: the function f() is defined on an 11 dimensional set. I want to evaluate the function on the vertices of the an 11 dimensional grid. For a grid size `h`, possible values for the entries of the array `x[]` could be `0`, `h`, `2*h`, ..., `n*h` = val_1, val_2, ...,val_n . So in the beginning `f(val_1, val_1, ..., val_1)` should be evaluated, then `f(val_1, val_1, ...,val_1, val_2)`, ... and in the and `f(val_n, val_n, ..., val_n)`. I don't care about the order actually, but I do care about speed, because there are many such tuples. To be precise, there are n^11 such tuples. So for n=10 `f()` has to evaluated 10^11 times. My computer can evaluate `f()` approximately 5*10^6 times per second, so for n=10 the evaluation of `f()` takes 5 hours. That's why I'm searching for the most efficient way to implement it.

Original source