I am using Heap's algorithm for generating all the permutations of a list, but for some reason my implementation is not working. Specifically, it produces the correct number of permutations, n!, but it is missing some and fills in the gaps with copies of previous permutations. Here is what it produces with 3 items: (first instance of duplicates marked with f, second instance with s, third with t, marking done by me not code)
0, 1, 2,
1, 0, 2,
2, 1, 0, f
1, 2, 0, f
2, 1, 0, s
1, 2, 0, s
This is what it produces with four items:
0, 1, 2, 3,
1, 0, 2, 3,
2, 1, 0, 3, f
1, 2, 0, 3, f
2, 1, 0, 3, s
1, 2, 0, 3, s
3, 1, 2, 0,
1, 3, 2, 0, f
2, 1, 3, 0,
1, 2, 3, 0, f
0, 1, 3, 2,
1, 0, 3, 2,
1, 3, 2, 0, s
0, 3, 2, 1,
2, 3, 1, 0, f
0, 3, 1, 2, f
3, 2, 1, 0, f
1, 2, 3, 0, s
2, 3, 1, 0, s
0, 3, 1, 2, s
3, 2, 1, 0, s
1, 2, 3, 0, t
2, 3, 1, 0, t
0, 3, 1, 2, t
Here is my code:
vector<vector<int>> permutations;
void GenerateAllPermutations(vector<int> v, int size)
{
// if size becomes 1 then adds on the obtained permutation
if (size == 1) {
permutations.push_back(v);
return;
}
for (int i = 0; i < size; i++) {
GenerateAllPermutations(v, size - 1);
// if size is odd, swap first and last element
if (size % 2 == 1)
{
iter_swap(v.begin(), v.begin() + v[size - 1]);
}
// If size is even, swap ith and last element
else
{
iter_swap(v.begin() + i, v.begin() + v[size - 1]);
}
}
}
int main()
{
vector<int> v = { 0, 1, 2, 3 };
GenerateAllPermutations(v, v.size());
// prints all the generated permutations
for (int i = 0; i < permutations.size(); i++)
{
for (int x = 0; x < permutations[i].size(); x++)
{
cout << permutations[i][x] << ", ";
}
cout << endl;
}
}