Sunday, January 15, 2012

Random Number Generator

Given a list, L, of size k. L contains elements between 1 and n. Also given a function RND() such that this function returns a number between 1 and INT_MAX.
Now generate number between 1 and n, using RND(), such that the element should not be there in the list L. All elements should have a uniform probability.
OR

k distinct integers [0, N)
Select a random no [0,N) which is not in this k distinct list.


Example:
[4, 6, 9]
Choose a random no between 0 - 9 which is not 4, or 6, or 9.


Valid output: 2
Invalid output: 6



Approach:
N = 10;
L = {1,2,3,4,5}
K = L.length;
Generate random number R = RND()%(N-K) + 1;
Let R = 2;
now iterate through L and for every number greater or equal than 2, increase R by 1,
2,3,4,5 are greater than or equal to 2. 
L[1] >= R(2) = ++R = 3
L[2] >= R(3) = ++R = 4
L[3] >= R(4) = ++R = 5
L[4] >= R(5) = ++R = 6
So now we have final random number R = 6;

Lets  see another example:



K = [2, 3, 6, 9, 12, 17, 20, 21]
N = 30
r = rand (22) = 16



Available: [1, 4, 5, 7, 8, 10, 11, 13, 14, 15, 16, 18, 19, 22, 23, 24, 24, 26, 27, 28, 29, 30]
So r = 24 in this case. 


It is important that k be in increasing order for this method to work. If you take a second look at the method, you will see that it isn't just incrementing r for each below it in k, it is incrementing based on its previous incrementend value.
So for the above situation, the iterations will be: 


k[0] -> 16 > 2, so r = 17
k[1] -> 17 > 3, so r = 18
k[3] -> 18 > 6, so r = 19
k[4] -> 19 > 9, so r = 20
k[5] -> 20 > 12, so r = 21
k[6] -> 21 > 17, so r = 22
k[7] -> 22 > 20, so r = 23
k[8] -> 23 > 21, so r = 24


So finally here we have r=24 as the answer.

No comments:

Post a Comment