I try to create a program for generate all permutation (for example input nr=3 and result will be 1 2 3, 1 3 2, 2 3 1 ...). I try to use non-recursive backtracking. I don't understand why the program is not function propertly.
Here is my code:
It doesn't matter if it's in beginner, or general C++. But you need to provide us with some more information to help us help you fix the problem.
Alot of the volunteers here don't have time to take alot of code, compile it and analyse it to see what is wrong. We rely on you telling us what the problem is so we can quickly scan the code for issues to help you solve it :)
int main(int argc, char *argv[])
{
int n;
cout<<"nr: ";
cin>>n;
generate_permutations(n);
return 0;
}
[/c0de]
the program not generate all permutation....this is a big problem :)
:) Thats a nicer, shorter implementation. Unfortunately, I can see a few issues in your algorithim that makes it impossible for it to generate them all.
You will push 1 number onto it, then you will run through your next k-loop with only 1 number in your vector. And you will do this until you have N numbers. But you shouldn't be running your K loop until you have N numbers, not upto N numbers.
is to push the first number in a set of combinations. For a set a combinates i means like {(1,2,3), (1,3,2)}. Another set is {(2,1,3), (2,3,1)}. (for nr=3)
The main issue with your method of generating them is that you are not storing any information between each set you generate.
So how do you know if you have done 213 or 231? That link I provided shows you a very simple way to generate all the permutations. The code is small and tidy. You can easily modify that to use a vector instead of a static array. It also shows you have to store static variables between runs to ensure you get every combination and don't generate the same combination twice.
Without storing information you are only going to be moving forward, and will miss some combinations. Which I suspect is what yours is doing?
You are incrementing K from 1->N. So your algorithm is always moving forward. Thats why the 2nd number in your answer is always N+1 (where I!=N, others answer is 1). See what I mean?