1

This question is extended from this Algorithm to generate integer sets fulfills restrictions, in the answer I learned the formal term of this problem, and the recursive algorithm described in that answer also gives me the desired sequence - as much large numbers located in the front as possible, for example, we will get the following output for $F(7,3,4)$:

  • 4>2>1
  • 3>3>1
  • 3>2>2

So here is the question, given a valid combination, is it possible to get its index in the result set without generating the whole result set and searching for it?

Li Wang
  • 33
  • 4

1 Answers1

1

This is called ranking combinatiorial objects, in this case combinations. Ranking and unranking algorithms exist for various simple combinatorial objects and even a general ranking algorithm exists for arbitrary combinatorial objects given that computing the number of objects matching certain criteria is feasible and there is a total ordering (eg lexicographic ordering).

For combinations, a reference is Algorithms for Unranking Combinations and Other Related Choice Functions, Zbigniew Kokosinski 1995

Assuming a lexicographic ordering among combinations of $K$ from $N$ the following algorithm can be used (which runs in $O(K)$ time assuming binomial computations are cheap):

Assuming the combination is given as an array (item) of length $K$ and where

$$item[0]<item[1]<\dots<item[K-1]$$

and each $0 \leq item[i] \leq N-1$

(If you want the combination in reverse order simply change the algorithm below to match in reverse order and skip last step. Also since your combinations take values between $1$ and $N$ you might want to subtract $1$ from below algorithms, where $item[i]$ is used)

$index = 0$

for $i=1$ to $K$:

____ $c = N-1-item[i-1]$

____ $j = K+1-i$

____ if $j \leq c$ then $index \leftarrow index+\binom{c}{j}$

Finally: $index \leftarrow \binom{N}{K}-1-index$

Note: The algorithm above can be modified to rank combinations with repeated/duplicate elements. Ie

$$item[0] \leq item[1] \leq \dots \leq item[K-1]$$

One needs to replace the counts used to represent combinations with repeated elements instead of binomials which count combinations with unique elements.

$index = 0$

$N \leftarrow N+K-1$

for $i=1$ to $K$:

____ $c = N-1-item[i-1]-i+1$

____ $j = K+1-i$

____ if $j \leq c$ then $index \leftarrow index+\binom{c}{j}$

Finally: $index \leftarrow \binom{N}{K}-1-index$

In essense ranking combinations is a bijection from $N,K$ combinations to natural numbers $0 \dots \binom{N}{K}-1$. This defines a combinatorial number system.

Algorithms above are modified to match my use case (for my combinatorics library Abacus) where combinations take values $0 \dots N-1$ and are non-decreasing. For your use case you can modify them to match wikipedia article.

Nikos M.
  • 1,016
  • 7
  • 16