I am trying to find the most efficient way to find the permutation in the set of '0' and '1' given the index.
Ex: given l = [0, 0, 1, 1]. All permutations in ascending order are {0011, 0101, 0110, 1001, 1010, 1100}. These elements are indexed from 0 → 5. Given the index = 2, the result is 0110.
I found an algorithm here that introduces an integer multiset (for example, l = [1, 2, 2]). Its algorithm is efficient (O (N ^ 2)). However, my multiset consists only of "0" and "1" and requires O (N) or less. N - list length
Could you kindly help me. Please note that my real test is big (len (l) - 1024), so the intertool library is not suitable. I try to speed it up as much as possible (e.g. using gmpy2 ...)
Based on 1 , my attempt is this: O (N ^ 2)
from collections import Counter from math import factorial import gmpy2 def permutation(l, index): if not index: return l counter = Counter(l) total_count = gmpy2.comb(len(l), counter['1']) acc = 0 for i, v in enumerate(l): if i > 0 and v == l[i-1]: continue count = total_count * counter[v] / len(l) if acc + count > index: return [l[i]] + permutation(l[:i] + l[i + 1:], index - acc) acc += count raise ValueError("Not enough permutations") l = ['0', '0', '1', '1'] index = 2 print (l, index) --> result = [0, 1, 1, 0]
Thanks in advance.