PermutationsΒΆ

A permutation of a sequence \(\mathbf{S}\) is simply the members of \(\mathbf{S}\) arranged in some order. For example, a permutation of the integers 1 through \(n\) would be those values arranged in some order. If the sequence contains \(n\) distinct members, then there are \(n!\) different permutations for the sequence. This is because there are \(n\) choices for the first member in the permutation; for each choice of first member there are \(n-1\) choices for the second member, and so on.

Sometimes one would like to obtain a random permutation for a sequence, that is, one of the \(n!\) possible permutations is selected in such a way that each permutation has equal probability of being selected. A simple function for generating a random permutation is as follows.

//Randomly permute the values in array
void permute(int data[], int n) {
  for (int i = n; i > 0; --i) {
    int j = std::uniform_int_distribution<int> {0, i-1} (eng);
    std::swap(data[i-1], data[j]);  // swap data[i-1] with a random
  }                                 // position in the range 0 to i-1.
}

Here, the \(n\) values of the sequence are stored in positions 0 through \(n-1\) of array data. Function swap exchanges elements in array data, and uniform_int_distribution returns an integer value uniformly distributed in the range 0 to \(i-1\).

Randomly shuffling a range of data is a common enough activity that it is implemented in the standard library. The shuffle function does what our permute function does, but a bit more generically.

std::shuffle(std::begin(data), std::end(data), eng);

Instead of an entire array it takes a range of data and a random number generator.

You have attempted of activities on this page