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
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
#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) );