In this post, I want to show you a method to generate sorted permutations of a set. We will focus on generating these permutations in lexicographic or numeric order. There are several ways to do this, but some are better than others in terms of efficiency.

We’ll also look at a method to obtain a permutation at an arbitrary position in our lexicographically ordered sequence. With this method, we can generate the permutation we’re looking for more directly. We won’t need to generate any of the previous permutations in the sequence that come before our target one.

Let’s start by refreshing our memory on what a permutation is.

What Is a Permutation?

From combinatorics, a permutation–also called “order”–is the number of rearrangements of elements in a set. The number of permutations on a set of n elements is given by n! (n factorial). For example, in the set {1, 2, 3} there are 3! = 3x2x1 = 6 permutations: {1 ,2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, and {3, 2, 1}.

The number of ways to rearrange a subset of k elements out of a set of n elements is given by :

This formula is easily derived from our previous definitions. Let’s follow a concrete example to illustrate this. Suppose we want to find the number of ways to arrange 4 books from a collection of 10. According to our formula above, we have:

We can think about this in the following way. In the numerator, we have the number of ways to arrange 10 books–that is 10!. But, we only care about the first 4 ways. So, we divide out the remaining 6 ways–or ( 10-4)! = 6!:

Image for post

Finally, keep in mind that in a permutation, we count all possible orderings in a set.

Generating Permutations

We can generate permutations using different methods. And, depending on the method we choose, the order of the resulting permutations will change. Also, some methods will be more efficient than others. Robert Sedgewick concluded in his survey paper Permutation Generation Methods that the fastest algorithm to generate permutations is Heap’s algorithm. However, the resulting rearrangements form this method are not in lexicographic order.

Permutations in Lexicographic Order

In our case, we want to list them in lexicographic-or numerical-order. As an example, let’s generate the permutations of the set {0 1 2}. We take the smallest number, 0, and put it at the front then we append the remaining 1 and 2. This gives us the first permutation {0 1 2}. Next, keeping 0 in front, we rearrange 1 and 2: {0 2 1}. We repeat the process, but now with 1 at the front. So, we obtain permutations {1 0 2} and {1 2 0}. Finally, we repeat with 2 at the front: {2 0 1} and {2 1 0}. The resulting permutations list is the following.

#math #programming #coding #algorithms #software-engineering

Efficient Permutations In Lexicographic Order
1.20 GEEK