What is the fastest way to write a function nthPermutation[xs_List, n_Integer] which is equivalent to Permutations[xs][[n]] but does not explicitly compute all the permutations of xs? This feature seems conspicuously absent from Mathematica.
I have a basic implementation below which almost does what I want, but does not preserve the original ordering of xs (it is instead equivalent to Permutations[Sort[xs]][[n]]), does not check that n is in bounds, and is almost certainly not the fastest method.
nthPermutation[{}, 1] = {}; nthPermutation[xs_List, n_Integer] := Block[{u = Union[xs], p, i = 1}, p = Accumulate[numPermutations[DeleteCases[xs, #, {1}, 1]] & /@ u]; While[n > p[[i]], i++]; Prepend[nthPermutation[DeleteCases[xs, u[[i]], {1}, 1], If[i == 1, n, n - p[[i - 1]]]], u[[i]]]]; Edit: I should clarify that, if possible, nthPermutation[xs, n] should be equivalent to Permutations[xs][[n]] whenever it is defined, even with repeated and out-of-order elements in xs. For example, we should have that Permutations[{1, 3, 1, 2, 3}][[20]] === nthPermutation[{1, 3, 1, 2, 3}, 20] === {3, 2, 1, 3, 1}.
nthPermutationcode above. The problem is, that ranking function gives the permutations in lexicographic order, while the ranking function Mathematica uses internally is decidedly not lexicographic--examine the output ofPermutations[{1, 3, 1, 2, 3}]and you'll see what I mean. $\endgroup$