JavaScript Snippet

Generate Unique Random Integers Without Bias

Difficulty: Medium

Picking N unique random integers from a range sounds simple, but the right algorithm depends on how N compares to the range size. Retry-into-a-Set is fine when N is small relative to the population, but as N approaches the range size retries dominate and a partial Fisher-Yates shuffle becomes the right answer. For streams of unknown size, reservoir sampling is the only option that gives uniform probability in a single pass.

Code Snippets
/

Generate Unique Random Integers Without Bias

Generate Unique Random Integers Without Bias

Picking N unique random integers from a range sounds simple, but the right algorithm depends on how N compares to the range size. Retry-into-a-Set is fine when N is small relative to the population, but as N approaches the range size retries dominate and a partial Fisher-Yates shuffle becomes the right answer. For streams of unknown size, reservoir sampling is the only option that gives uniform probability in a single pass.

JavaScript
Medium
3 snippets
arrays
set
randomized-algorithms

501 views

12

When the population is much larger than the count you need (say n / max < 0.5), each random draw is almost guaranteed to be new. The expected number of retries to fill the Set is n + small constant, so this is O(n) in practice and the code stays readable. Throw early if the caller asks for more uniques than the range allows, otherwise the loop never terminates. This is the right default for picking 5 of 100, 50 of 10000, or any case where you are sampling sparsely from a large pool.