Interview Question
7 * (rand()/rand()) is not right.
There's someone have posted, as far as I know, you may make two succesive call of rand()to produce a number. so you get a random number from 1 to 25, the range is larger than [1,7]. if the number come out is within [8,25] you can simply ignore it.
int getRand() {
int num = 0;
do {
num = (rand()-1)*5+rand();
}while(num > 7);
return num;
}
of course, you are recommented make 5, 7 as parameter of the fuction #getRand().
May you good luck!
/Dam775
None of the ideas above would work because implicit in the question is the fact that the output should be uniformly distributed.
But using rand5, you can get a 0 or a 1 uniformly dist. (if (rand5=1 or 2) output 0, if(rand5=3 or 4) output 1, else try again). calling this 3 times you can get any number from 0 to 7 (in binary). Just ignore the 0 (i.e. generate again)
This would do it. Not the most elegant solution, but WTF.
I tried:
- shassant2 December 22, 2009Round(7 * (rand()/rand()))