How to generate a single instance of multichoose (stars and bars)

496 Views Asked by At

So we know that if I have $k$ balls and $n$ buckets, I have $\binom{n+k-1}{k}$ unique ways to allocate the balls. Let's say $n=4$ and $k=2$ then I have $\binom{5}{2}=10$ ways. All possible allocations are shown below.

0002 0011 0020 0101 0110 0200 1001 1010 1100 2000

My question is, then, given $n$ and $k$, how can I generate each allocation based on some index? Input would be $n$,$k$, and some $i$ and the output would be the allocation.

For example, code(4,2,1) would return 0002, the first instance of $n=4$ and $k=2$ and code(4,2,8) would return 1010. Any help on where to look would be great. Thank you

1

There are 1 best solutions below

0
On BEST ANSWER

The combinatorial number system provides a way to encode a $k$-combination into a single number (counting from $0$), namely its position in the lexicographic order of representation as a decreasing list of $k$ elements. The reverse operation which you are after (turning the index into the $k$-combination at that position) is also straightforward. Finally use the stars-and-bars bijection to turn a $k$ combination of $n+k-1$ into an allocation of $k$ balls into $n$ buckets (essentially read the $0$'s as bars, and add up runs of consecutive $1$'s as a bucket contents).