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:
- naive method: generating a number and checking if it’s already in the array. O(n^2)
- linear shuffle: generate sequence 0 to 8000, shuffle, take the first 1000. O(n)
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
kswaps, the firstknumbers are a random sample of sizekfrom the complete set.