I am trying to find an efficient algorithm to find permutation of a multiset, given an index.
Ex: given {1, 3, 3}
. All permutations in an ascending lexicographic order are {133, 313, 331}
. These elements are indexed as {0, 1, 2}
. Given index=2
, the result is 331.
I found an algorithm to find permutation of a set given a lexicographic index. His algorithm is efficient: O(n^2).
However, the algorithm is tested on a proper set (e.g. {1, 2, 3}
), and not correct on my test. I describe his python code here so that you can easily follow.
from math import factorial, floor #// python library
from math import factorial, floor #// python library
i=5 #// i is the lexicographic index (counting starts from 0)
n=3 #// n is the length of the permutation
p = range(1,n+1) #// p is a list from 1 to n
for k in range(1,n+1): #// k goes from 1 to n
d = i//factorial(n-k) #// use integer division (like division+floor)
print(p[d]),
p.remove(p[d]) #//delete p[d] from p
i = i % factorial(n-k) #// reduce i to its remainder