Computationally efficient way to number permutations with repetitions

145 Views Asked by At

I need a bijective function/algorithm that can quickly and efficiently map a permutation into an integer and then another function that restores that permutation from this integer.

Example:

Let's say I have the numbers

M={2,2,5,4}

The first function f(M, permutation) should do something like this

2 2 5 4 -> 1
2 2 4 5 -> 2
2 4 2 5 -> 3
2 5 2 4 -> 4
2 4 5 2 -> 5
2 5 4 2 -> 6
5 2 2 4 -> 7
5 2 4 2 -> 8
5 4 2 2 -> 9
4 2 2 5 -> 10
4 2 5 2 -> 11
4 5 2 2 -> 12

The second function $f^{-1}$(M, permutation_number) should reverse the process

1 -> 2 2 5 4
2 -> 2 2 4 5
3 -> 2 4 2 5
4 -> 2 5 2 4
5 -> 2 4 5 2
6 -> 2 5 4 2
7 -> 5 2 2 4
8 -> 5 2 4 2
9 -> 5 4 2 2
10 -> 4 2 2 5
11 -> 4 2 5 2 
12 -> 4 5 2 2

There is no limit how many elements can be indistinguishable in the set M. M is basically a random set of numbers. If needed, M can be ordered in a predictable manner (for example ascending/descending) before being passed to the first function.

The order of permutations is not important. As long as I can translate back and forth without ambiguities, it will be fine.

It's important that there is no gaps in the integers: if there is 12 combinations, the permutation numbers should go from 1 to 12 (or from 0 to 11). Also, this should be quickly computable in both directions, even for large sizes of M (let's say 2000 Elements in M).

For simplicity sake let's ignore integer overflow in case the number of combinations exceeds a 64 bit integer. This is an implementation problem which is probably easy to fix by using special data structures.