(Not logged on) | Register | Log On

You can subscribe to this discussion group using an RSS feed reader. techInterview Discussion

Answers to technical interview questions. A part of TechInterview.org

A part of techInterview.org: answers to technical interview questions.

Your host: Michael Pryor

Random number generation

Given a function rand5() which can generate numbers 1-5 with a euqal probability, how to generate number 1-7 with equal probability using rand5()?
zdd Send private email
Thursday, July 08, 2010
 
 
<XKCD>
int getRandomNumber() {
  return 4; // chosen by fair die roll.
    // guaranteed to be random.
}
</XKCD>
d Send private email
Friday, July 09, 2010
 
 
Use rand5 twice, then you have a number n from 1 to 25 equally likely. If n is less than or equal to 21, then return (n-1)%7+1, otherwise try again.
jdk Send private email
Friday, July 09, 2010
 
 
That's the basic idea. The optimal approach (counting expected calls to rand5()) is a bit more involved.
d Send private email
Friday, July 09, 2010
 
 
Call rand5 two times and then you get a number between 0 to 24..
Divide the spectrum evenly as...0-2 : 1; 3-5 : 2, ...,18-20 : 7...for the rest of the values 21,22,23,34 repeat this procedure...i think this will give you a random distribution

Saturday, July 10, 2010
 
 
Hi jdk, how do you do this?
Use rand5 twice, then you have a number n from 1 to 25 equally likely?

Saturday, July 10, 2010
 
 
d Send private email
Saturday, July 10, 2010
 
 
jdk:
 
how you will generate a prinme number [ex: 17, 19...]with two rand5 funtion() ?
gun0m gun0m Send private email
Thursday, August 05, 2010
 
 
By doing 5 * (rand5() - 1) + rand5() instead of rand5() * rand5().
d Send private email
Thursday, August 05, 2010
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz