nthPermutation

Permutes range into the perm permutation. The algorithm has a constant runtime complexity with respect to the number of permutations created. Due to the number of unique values of ulong only the first 21 elements of range can be permuted. The rest of the range will therefore not be permuted. This algorithm uses the Lehmer Code.

The algorithm works as follows:

1 auto pem = [4,0,4,1,0,0,0]; // permutation 2982 in factorial
2     auto src = [0,1,2,3,4,5,6]; // the range to permutate
3 
4     auto i = 0;                    // range index
5     // range index iterates pem and src in sync
6     // pem[i] + i is used as index into src
7     // first src[pem[i] + i] is stored in t
8     auto t = 4;                    // tmp value
9     src = [0,1,2,3,n,5,6];
10 
11     // then the values between i and pem[i] + i are moved one
12     // to the right
13     src = [n,0,1,2,3,5,6];
14     // at last t is inserted into position i
15     src = [4,0,1,2,3,5,6];
16     // finally i is incremented
17     ++i;
18 
19     // this process is repeated while i < pem.length
20 
21     t = 0;
22     src = [4,n,1,2,3,5,6];
23     src = [4,0,1,2,3,5,6];
24     ++i;
25     t = 6;
26     src = [4,0,1,2,3,5,n];
27     src = [4,0,n,1,2,3,5];
28     src = [4,0,6,1,2,3,5];

ref
Range
nthPermutation
(
Range
)
(
auto ref Range range
,
const ulong perm
)
if ()

Parameters

range Range

The Range to permute. The original ordering will be lost.

perm ulong

The permutation to permutate range to.

Return Value

Type: Range

The permuted range.

Examples

auto src = [0, 1, 2, 3, 4, 5, 6];
auto rslt = [4, 0, 6, 2, 1, 3, 5];

src = nthPermutation(src, 2982);
assert(src == rslt);

Meta

Suggestion Box / Bug Report