views:

67

answers:

2

I am looking for an algorithm (or a C-like implementation, no itertools available) which generates all tuples [a_0 a_1 ... a_(n-1)] such that 0 <= a_i <= i + 1. Pointers to literature are also welcome.

+3  A: 

something like this?

void printTuples (int n, int[] a, int i=0) {
    if (i == n) {
        //print a
        return;
    }
    for (int j=0; j<=i+1; j++) {
        a[i] = j;
        printTuples (n, a, i+1);
    }
}
Amir Rachum
you need j<=i+1 probably in loop condition.
Vladimir
@Vladimir fixed, thanks.
Amir Rachum
I also assumed a_i>=0.
Amir Rachum
In this solution a[0] <= 0 but should be <= 1. Thanks anyway, was pretty fast!
John
@John if this helped you, please accept the answer.
Amir Rachum
I accept the answer because it helped me. Thank you! However the solution is not correct. Your function gives (for n=3) 000,001,002,010,011,012.
John
@John did you try it after the fix?
Amir Rachum
tried mine now, it gives 000,001,002,003,010,011,012,013,020,021,022,023,100,101,102,103,110,111,112,113,120,121,122,123
Amir Rachum
Fantastic! Now I give you also one point. Great work!
John
Oh, I do not have enough points. Sorry. I come back later this year.
John
A: 

It's called backtracking. Search wikipedia about it. You can do it both recursive or iterative.

Amir, he wants between 0 and i + 1, not between 0 and i. And i think passing arrays on the stack is slower thant accesing them as global.

I think you want something like this:

int a[YOUR_LENGTH];

void backtracking (int n, int counter) {
    if (counter == n) {
        // do whatever
        return;
    }
    for (int j = 0; j <= counter + 1; ++ j) {
        a[counter] = j;
        backtracking(n, counter + 1);
    }
}
Teodor Pripoae
I fixed the <= problem and arrays are passed as pointers. any way, I don't know on what language and platform he will use, so it's not really relevant.
Amir Rachum
Usually it's better to avoid globals. It's backtracking, the couple milliseconds you might win by using a global are definitely not worth it.
IVlad
Teodor, you forgot to replace the 'i' from Amir's solution by 'counter', no? Thanks for the information on 'backtracking'.
John
Thank you John, i've edited it.
Teodor Pripoae
Hmm, I am a pain in the neck, I know, but there is still an 'i'. ... and a missing '}'. But I will give you a point when I am above the 15 point limit imposed by SO.
John