Most efficient way of randomly choosing a set of distinct integers

后端 未结 8 717
囚心锁ツ
囚心锁ツ 2020-12-01 07:04

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:<

8条回答
  •  不思量自难忘°
    2020-12-01 07:29

    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:

    1. Keep a sorted list l of number picked so far, initially empty.
    2. Pick a random number x between 0 and maxValue - (elements in l)
    3. For each number in l if it smaller than or equal to x, add 1 to x
    4. Add the adjusted value of 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:

    1. Keep a set s of element picked so far, initially empty.
    2. Pick a number at random between 0 and maxValue.
    3. If the number is not in s, add it to s.
    4. Go back to step 2 until s has n elements.

    In practice if n is small and maxValue is large this will be good enough for most purposes.

提交回复
热议问题