Here is an implementation in Mathematica, from the package Combinatorica. The semantics are fairly generic, so I think it is helpful. Please leave a comment if you need anything explained.
UnrankKSubset::usage = "UnrankKSubset[m, k, l] gives the mth k-subset of set l, listed in lexicographic order."
UnrankKSubset[m_Integer, 1, s_List] := {s[[m + 1]]}
UnrankKSubset[0, k_Integer, s_List] := Take[s, k]
UnrankKSubset[m_Integer, k_Integer, s_List] :=
Block[{i = 1, n = Length[s], x1, u, $RecursionLimit = Infinity},
u = Binomial[n, k];
While[Binomial[i, k] < u - m, i++];
x1 = n - (i - 1);
Prepend[UnrankKSubset[m - u + Binomial[i, k], k-1, Drop[s, x1]], s[[x1]]]
]
Usage is like:
UnrankKSubset[1, 4, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
{1, 2, 3, 5}
As you can see this function operates on sets.
Below is my attempt to explain the code above.
UnrankKSubset is a recursive function with three arguments, called (m, k, s):
m
an Integer, the "rank" of the combination in lexigraphical order, starting from zero.
k
an Integer, the number of elements in each combination
s
a List, the elements from which to assemble combinations
There are two boundary conditions on the recursion:
for any rank m
, and any list s
, if the number of elements in each combination k
is 1
, then:
return the m + 1
element of the list s
, itself in a list.
(+ 1
is needed because Mathematica indexes from one, rather than zero. I believe in C++ this would be s[m] )
if rank m
is 0
then for any k
and any s
:
return the first k
elements of s
The main recursive function, for any other arguments than ones specified above:
local variables: (i
, n
, x1
, u
)
Binomial
is binomial coefficient: Binomial[7, 5]
= 21
Do:
i = 1
n = Length[s]
u = Binomial[n, k]
While[Binomial[i, k] < u - m, i++];
x1 = n - (i - 1);
Then return:
Prepend[
UnrankKSubset[m - u + Binomial[i, k], k - 1, Drop[s, x1]],
s[[x1]]
]
That is, "prepend" the x1
element of list s
(remember Mathematica indexes from one, so I believe this would be the x1 - 1
index in C++) to the list returned by the recursively called UnrankKSubset function with the arguments:
m - u + Binomial[i, k]
k - 1
Drop[s, x1]
Drop[s, x1]
is the rest of list s
with the first x1
elements removed.
If anything above is not understandable, or if what you wanted was an explanation of the algorithm, rather than an explanation of the code, please leave a comment and I will try again.