Random number generation [duplicate]
Possible Duplicate:
Expand a random range from 1-5 to 1-7
Hi, This question is taken from http://blog.seattleinterviewcoach.com/2009/02/140-google-interview-questions.html
Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.
I am not getting a way to generate all random numbers 1 to 7 with almost equal probability by using 1 to 5 random generator.
Coul开发者_开发问答d anyone pls solve it ?
I assume that the function you're given provides uniformly distributed-numbers and it is a strict requirement that the function you need to write also returns uniformly-distributed numbers.
The following pseudo-code illustrates the standard technique (called rejection sampling):
do {
rand25 = (rand5() - 1) * 5 + rand5; // 1-25
} while (rand25 > 21);
return (rand25 - 1) / 3 + 1;
What about func() + func() % 3 ?
精彩评论