Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to generate 1000 distinct integers in the range [0,8000]? [duplicate]

Possible Duplicate:
How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N

What are some alternative methods to generate 1000 distinct random integers in the range [0,8000] as opposed to the following:

  1. naive method: generating a number and checking if it's already in the array. O(n^2)
  2. linear shuffle: generate sequence 0 to 8000, shuffle, take the first 1000. O(n)
like image 713
snap Avatar asked Dec 06 '22 03:12

snap


1 Answers

You can use a partial Fisher-Yates shuffle implemented using swaps. One of the nice features of this algorithm is that if you stop after k swaps, the first k numbers are a random sample of size k from the complete set.

like image 149
Mark Byers Avatar answered Jan 12 '23 00:01

Mark Byers