Hi,
I am trying to write a program to generate permutations of an integer from 0 to a certain n(specified by the user).
So for example -
Code:
n = 1
1
n = 2
1 2
2 1
n = 3
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
and soo on...
My program works works upto n = 3 but after that it starts repeating the output, here is a sample run from program -
Code:
1
1
2
12
21
3
123
213
231
321
312
132
4
1234
2134
2314
2341
3241
3421
3412
4312
4132
4123
1423
1243
//REPEAT
1234
2134
2314
2341
3241
3421
3412
4312
4132
4123
1423
1243
Here is my program, can someone let me know whats wrong ?
Code:
void GeneratePermutations(int input)
{
int* arr = new int[input];
for(int i = 1; i <= input; ++i){
arr[i - 1] = i;
}
int lim = fact(input);
int counter = 1;
for(int i = 0; i < lim; ++i)
{
for(int j = 0; j < input ; ++j)
cout << arr[j];
cout << endl;
swap(arr[counter - 1],arr[counter]);
counter = (counter + 1) % input;
if(counter == 0) counter = 1;
}
}
Thank you!