c++arrayspermutation

Using next_permutation on arrays of ints


Given some arrays, I'd like to loop over every possible permutation of these arrays:

Here's a minimal example:

#include <array>
#include <iostream>
//#include <random>
#include <algorithm>

using namespace std;

int main() {
    // Change the first number of the arrays to get a different number of permutations
    // (this is not wanted)
    array<int, 4> A = { 1,0,0,0 };
    array<int, 4> B = { -9,0,0,0 };
    array<int, 4> C = { 3,0,0,0 };
    array<int, 4> temp[3] = { A, B, C };

    int i = 1;
    do {
        cout << "This is the " << i++ << "-th permutation." << endl;
    } while (next_permutation(temp, temp + 3));
    // (it should yield 3! = 6 permutations but only yields 4)

    return 0;
}

However the number of looped permutations seems to be dependent on the starting value of the array (which is not a feature I wish to use in my project).

This is because next_permutation orders it's elements in lexicographical order.

How can I use this function to get all permutations of the given Arrays? Or do I have to use a different method entirely?

I also know about this answer, but I'd like to avoid sorting my arrays beforehand, since I'm planning to work with a large number of arrays.

Thanks!


Solution

  • You can do by indirectly mapping the sorted array { 0, 1, 2 }

    #include <array>
    #include <iostream>
    //#include <random>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        array<int, 4> A = { 1,0,0,0 };
        array<int, 4> B = { -9,0,0,0 };
        array<int, 4> C = { 3,0,0,0 };
        array<int, 4> temp[3] = { A, B, C };
        int ijk[] = { 0, 1, 2 };
    
        int i = 1;
        do {
            cout << "This is the " << i++ << "-th permutation." << '\n';
            cout << temp[ijk[0]][0] << "  " << temp[ijk[1]][0] << "  " << temp[ijk[2]][0] << '\n';
        } while (next_permutation(ijk, ijk + 3));
    }
    

    Output:

    This is the 1-th permutation.
    1  -9  3
    This is the 2-th permutation.
    1  3  -9
    This is the 3-th permutation.
    -9  1  3
    This is the 4-th permutation.
    -9  3  1
    This is the 5-th permutation.
    3  1  -9
    This is the 6-th permutation.
    3  -9  1