I am currently working on a program in C, that needs to calculate the permutations
of a n integer array. The approach that I have taken is using recursion, using a n-element array of counters incrementing the correct value each recursion,
so the subroutine calls itself x (x being the max # of permutations) number of times returning the next permutation.
For example: Information known ahead of time: n = 3(could be any value); n_array[0] = 3 (could be any value from 1 to 9), n_array[1] = 3, n_array[2] = 3:
so first permutation (does not have to be in this order):
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 1
1 1 1 etc.
That being said, I attempted to write a loop within the recursive function that looks like this,
for(i = 0; i <n; i++) {
if(i == n-1) {
count[i]++;
}
if(count[i] == n_array[i]) {
count[i] = 0;
count[i-1]++;
}
}
which gives the following:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0 -> incorrect
1 0 1
1 0 2 etc.
I realize what my loop is doing, but I can't think of a way to fix
it, any fresh ideas would be appriciated. Thanks in advance.