Generate all possible permutations

Typical goal is to enumerate all possible permutations of a sequence of values. For example, the numbers 0,1,2,3 could result in the following lexicographical enumeration of 24 permutations.
0 1 2 3
0 1 3 2
0 2 1 3
0 2 3 1
0 3 1 2
0 3 2 1
1 0 2 3
1 0 3 2
1 2 0 3
1 2 3 0
1 3 0 2
1 3 2 0
2 0 1 3
2 0 3 1
2 1 0 3
2 1 3 0
2 3 0 1
2 3 1 0
3 0 1 2
3 0 2 1
3 1 0 2
3 1 2 0
3 2 0 1
3 2 1 0

If working with some other sequence of data values, it is possible to consider mutating that dirctly, but we will rely on an indirect approach based on the above permutations of the indices from 0, ..., n-1. If the original values are stored in data and we create the sequence perm of the indicies, then the item with index j in the permutated data set would be data[perm[j]].


C++

In C++, this is trivally done by using the <algorithm> library, which supports a next_permutation function. This can be used to mutate any bidirectionally sequential container (e.g., array, vector, string, list) to move from one permutation to the next lexicographically-smallest permutation; it has a return value that returns false if there is none (because the elements are in reverse order) and true otherwise.

To get all permutations, you should typically start with the elements in sorted order (or re-sort them if necessary). As a typical example, here is how to get all permutations of the numbers {0, ..., n-1}.

    #include <algorithm>
    #include <vector>    // of using vectors

    vector<int> perm;
    for (int j=0; j<n; j++)  perm.push_back(j);   // insert values 0, ..., n-1

    sort(perm.begin(), perm.end());     // useful if they weren't known to be sorted

    do {
       // process current permutation (but do not mutate it)
    } while ( next_permutation(perm.begin(), perm.end()) );
Please note that when using arrays, the proper syntax is the following
    #include <algorithm>

    int perm[n];                            // hard-wired for n
    for (int j=0; j<n; j++)  perm[j] = j;   // insert values 0, ..., n-1

    sort(perm, perm+n);     // useful if they weren't known to be sorted

    do {
       // process current permutation (but do not mutate it)
    } while ( next_permutation(perm, perm+n) );

Java

I do not see any similar functionality. We could write the equivalent functionality ourself (but have not yet done so).
Michael Goldwasser
Last modified: Tuesday, 31 August 2010