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:<
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 than maxValue
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 and maxValue
- (elements in l
)l
if it smaller than or equal to x
, add 1 to x
x
into the sorted list and repeat.If n
is very close to maxValue
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 to s
.s
has n
elements.In practice if n
is small and maxValue
is large this will be good enough for most purposes.