Creating function relating combination of distinct integers and an indexed range of ascending integers

17 Views Asked by At

I am trying to determine a mapping between an index of ascending integers, and distinct combinations of a range of integers.

I am using the itertools.combinations() function in python, and would like to access the index of a particular combination using the resulting sorted combination. Here is an example of the type of mapping I'm trying to achieve using some basic python code to generate indices and their corresponding combinations, formatted (f(w,x,y,z), distinct_combination(w,x,y,z)):

it = itertools.combinations(range(6),2)

for i in enumerate(it): print(i) Result:

(0, (0, 1, 2, 3))
(1, (0, 1, 2, 4))
(2, (0, 1, 2, 5))
(3, (0, 1, 3, 4))
(4, (0, 1, 3, 5))
(5, (0, 1, 4, 5))
(6, (0, 2, 3, 4))
(7, (0, 2, 3, 5))
(8, (0, 2, 4, 5))
(9, (0, 3, 4, 5))
(10, (1, 2, 3, 4))
(11, (1, 2, 3, 5))
(12, (1, 2, 4, 5))
(13, (1, 3, 4, 5))
(14, (2, 3, 4, 5))

Is there a closed-form function that I can generalize to accomplish this? I originally tried a multi-index, but when generalized to a large combinations object this was impractically slow.

As a potential starting point for determining such a function, while messing around and thinking about the problem, I realized that the number of times each first digit (d1) occurs can be represented as (n-(d1 + 1) choose p-1). In this example n = 6 and p = 4, so there are (5 choose 3) or 10 occurrences of 0, and 4 choose 3 or 4 occurrences of 1, and so-on. I could not determine an easy way to generalize this for d2-4 where values are repeated, or to convert this to an index.