Function Repository Resource:

PermutationFromIndex

Source Notebook

Give the permutation corresponding to a given length and lexicographic index

Contributed by: Ed Pegg Jr

ResourceFunction["PermutationFromIndex"][index,length]

gives the permutation with a given lexicographic index and length.

Details and Options

Permutations are considered to be in normal sorted order.
Lehmer codes are generated as an intermediary step.
The generating algorithm for Lehmer codes is as follows: For each number in the permutation, count how many subsequent values it exceeds.

Examples

Basic Examples (3) 

Give the first permutation of length 4:

In[1]:=
ResourceFunction["PermutationFromIndex"][1, 4]
Out[1]=

Give the last permutation of length 4:

In[2]:=
ResourceFunction["PermutationFromIndex"][24, 4]
Out[2]=

Give the 777th permutation of length 7:

In[3]:=
ResourceFunction["PermutationFromIndex"][777, 7]
Out[3]=

Scope (1) 

Permutations with an arbitrarily large lexicographic index can returned:

In[4]:=
ResourceFunction["PermutationFromIndex"][10^100, 72]
Out[4]=

Possible Issues (1) 

When an index for length n exceeds n!, the index is considered mod n!:

In[5]:=
ResourceFunction["PermutationFromIndex"][7777, 7]
Out[5]=
In[6]:=
ResourceFunction["PermutationFromIndex"][Mod[7777, 7!], 7]
Out[6]=

Neat Examples (1) 

Permutations halfway through the index:

In[7]:=
Grid[Table[
  ResourceFunction["PermutationFromIndex"][n! /2, n], {n, 2, 16}]]
Out[7]=

Version History

  • 1.0.0 – 20 December 2019

Related Resources

License Information