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
2010-07-26 14:04:22
you need j<=i+1 probably in loop condition.
Vladimir
2010-07-26 14:07:54
@Vladimir fixed, thanks.
Amir Rachum
2010-07-26 14:10:15
I also assumed a_i>=0.
Amir Rachum
2010-07-26 14:11:09
In this solution a[0] <= 0 but should be <= 1. Thanks anyway, was pretty fast!
John
2010-07-26 14:43:23
@John if this helped you, please accept the answer.
Amir Rachum
2010-07-26 15:00:58
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
2010-07-26 15:12:29
@John did you try it after the fix?
Amir Rachum
2010-07-26 15:14:35
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
2010-07-26 15:28:08
Fantastic! Now I give you also one point. Great work!
John
2010-07-26 15:31:51
Oh, I do not have enough points. Sorry. I come back later this year.
John
2010-07-26 15:32:44
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
2010-07-26 14:12:41
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
2010-07-26 14:15:11
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
2010-07-26 14:32:57
Teodor, you forgot to replace the 'i' from Amir's solution by 'counter', no? Thanks for the information on 'backtracking'.
John
2010-07-26 17:14:04
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
2010-07-26 18:48:25