Inspired by this SO post, I'd like to generate random bitstrings of a length $n$, having at most $k$ bits set for some $k$. Bitstrings should be selected uniformly at random amongst all possible bitstrings. (The original question also asks them to be unique, but that's easily handled with e.g. a set to catch duplicates).
Currently, I have a few approaches, none of which is ideal:
- For large $k$ ($\approx n/2$), just perform rejection sampling across all bitstrings of length $k$.
- For very small $k$, we can explicitly calculate the distribution of 1-bit counts via the binomial coefficients, then randomly select a target count from this distribution. (Generating bitstrings with exactly k bits set is much easier)
- For general use, choose a sequence of length $n$ out of a pool of $n$ 0s and $k$ 1s. While efficient, this approach is biased in favour of 1-bit counts near $k/2$.
Is there an efficient and correct algorithm for selecting random bitstrings with up to $k$ bits set?