This question has two parts, though since I'm trying to compe up with a Prolog implementation, solving one will probably immediately lead to a solution of the other one.
- Given a permutation of a list of integers
{1,2,...,N}
, how can I tell what is the index of that permutation in lexicographic ordering? - Given a number
k
, how can I calculatek
-th permutation of numbers{1,2...,N}
?
I'm looking for an algorithm that can do this reasonably better than just iterating a next permutation
function k
times. Afaik it should be possible to directly compute both of these.
What I came up with so far is that by looking at numbers from the left, I can tell how many permutations were before each number at a particular index, and then somehow combine those, but I'm not really sure if this leads to a correct solution.