Assuming that you cannot store k random numbers in memory, you will have to generate numbers in a strictly arbitrary order. One way to do this is to create a number from 0 to n / k. Name this number x . The next number you need to create is between x+1 and (nx) / (k-1). Continue this way until you type k numbers.
Basically, you divide the remaining range by the number of remaining values ββto generate, and then generate the number in the first section of that range.
Example. You want to generate 3 numbers from 0 to 99 inclusive. So you first generate a number from 0 to 33. Say you selected 10.
So now you need a number from 11 to 99. The remaining range consists of 89 values, and you have two values ββleft. So, 89/2 = 44. You need a number from 11 to 54. Say that you have chosen 36.
Your remaining range is from 37 to 99, and you have one number to choose. Therefore, select a number in random order between 37 and 99.
This will not give you a normal distribution, because once you select a number, it is impossible to get a number less than the next time you select it. But that may be enough for your purposes.
This pseudo code shows the main idea.
pick_k_from_n(n, k) { num_left = k last_k = 0; while num_left > 0 {
Note that this takes O (k) time and requires O (1) extra space.
Jim mischel
source share