Progressively generates all the permutations of the given size, in lexicographic order.

View versions (1)

Interface

#include <codecogs/maths/combinatorics/permutations/permutationlex.h>

using namespace Maths::Combinatorics::Permutations;

Overview

Consider the permutations of size n

\sigma = \left( \begin{array}{cccc} 1 & 2 & \ldots & n \cr
\sigma(1) & \sigma(2) & \ldots & \sigma(n) \end{array} \right)
(1)

and

\tau = \left( \begin{array}{cccc} 1 & 2 & \ldots & n \cr
\tau(1) & \tau(2) & \ldots & \tau(n) \end{array} \right)
(2)

Now consider the next two numbers in the numerical base n + 1, corresponding to each permutation

N_{\sigma} = \sum_{i = 0}^{n - 1} (n + 1)^i \sigma(n - i) \qquad
N_{\tau} = \sum_{i = 0}^{n - 1} (n + 1)^i \tau(n - i)
(3)

Then \tau is said to be the lexicographic succesor of \sigma if and only if N_{\tau} > N_{\sigma}.

This class progressively generates all the permutations of the given size, in lexicographic order, starting with the identical permutation.

Example:

#include <codecogs/maths/combinatorics/permutations/permutationlex.h>
#include <iostream>
int main()
{
  Maths::Combinatorics::Permutations::PermutationLex P(7);
  std::cout << "The first 5 lexicographic permutations of 7 elements:";
  std::cout << std::endl;
  for (int i = 0; i < 5; i++)
  {
    std::vector<int> alpha = P.getNext();
    for (int j = 0; j < alpha.size(); j++)
      std::cout << alpha[j] << " ";
    std::cout << "\t rank = " << P.getRank();
    std::cout << std::endl;
  }
  return 0;
}

Output:

The first 5 lexicographic permutations of 7 elements:
1 2 3 4 5 6 7    rank = 1
1 2 3 4 5 7 6    rank = 2
1 2 3 4 6 5 7    rank = 3
1 2 3 4 6 7 5    rank = 4
1 2 3 4 7 5 6    rank = 5

References

SUBSET, a C++ library of combinatorial routines, http://www.csit.fsu.edu/~burkardt/cpp_src/subset/subset.html

GPL Licence — free for non commercial use. See Licence details.

Members of PermutationLex

CLASS METHOD

PermutationLex

CLASS METHOD

getNext

generates the next permutation in lexicographic order; if all have been considered, it starts again from the first

CLASS METHOD

getRank

returns the rank of the current permutation