Cardchoose: simple, fast sampling without replacement
We present Cardchoose, a new algorithm for choosing k distinct natural numbers below n such that every set of k is equally likely. It draws a multiset of k values below n - k + 1 with a Pólya urn, then sorts it and converts it to a set by the stars and bars bijection. It is a few lines of integer arithmetic and a call to a standard sort, needs no memory beyond the output array, and takes O(k log k) time. We benchmark C++ and Rust implementations of it and twelve other algorithms over a wide range of n and k, for both sorted and random order output. No algorithm is fastest for every n, k, language and output order. Cardchoose is among the fastest for sorted output; for random output, algorithms that use a hash table are faster until the table outgrows the cache. Among the algorithms that need no memory beyond their output, it has the best worst-case time per number output over most of the range of k, and it is by far the simplest algorithm to perform acceptably across the whole range tested. GitHub: https://github.com/ciphergoth/sansreplace
Authors
- Paul Crowley (ORCID: https://orcid.org/0009-0005-8953-9081)
Publication Details
- Journal
- Zenodo (CERN European Organization for Nuclear Research)
- Published
- 2026-11-25
- DOI
- https://doi.org/10.5281/zenodo.24545117
- Primary Topic
- Algorithms and Data Compression
- Type
- preprint