I'm looking for the most efficient algorithm to randomly choose a set of n distinct integers, where all the integers are in some range [0..maxValue].
Constraints:
- maxValue is larger than n, and possibly much larger
- I don't care if the output list is sorted or not
- all integers must be chosen with equal probability
My initial idea was to construct a list of the integers [0..maxValue] then extract n elements at random without replacement. But that seems quite inefficient, especially if maxValue is large.
Any better solutions?
For small values of maxValue such that it is reasonable to generate an array of all the integers in memory then you can use a variation of the Fisher-Yates shuffle except only performing the first
n
steps.If
n
is much smaller thanmaxValue
and you don't wish to generate the entire array then you can use this algorithm:l
of number picked so far, initially empty.x
between 0 andmaxValue
- (elements inl
)l
if it smaller than or equal tox
, add 1 tox
x
into the sorted list and repeat.If
n
is very close tomaxValue
then you can randomly pick the elements that aren't in the result and then find the complement of that set.Here is another algorithm that is simpler but has potentially unbounded execution time:
s
of element picked so far, initially empty.maxValue
.s
, add it tos
.s
hasn
elements.In practice if
n
is small andmaxValue
is large this will be good enough for most purposes.Here is an optimal algorithm, assuming that we are allowed to use hashmaps. It runs in O(n) time and space (and not O(maxValue) time, which is too expensive).
It is based on Floyd's random sample algorithm. See my blog post about it for details. The code is in Java: