Monday, 12 November 2012

find random number between 1-7


Question:
Given a random number generator say r(5) generates number between 1-5 uniformly at random , use it to in r(7) which should generate a random number between 1-7 uniformly at random.


Solution:
int rand7() //random number from 1 - 7
{
    int r = 0;
    do
    {
       int a = rand(5) - 1; //uniformly at random from 0 to 4
       int b = rand(5) - 1;  //uniformly at random from 0 to 4
       r = 5*b + a;  //uniformly at random from 0 to 24
    }
    while (r >= 21); // in this event, we have to roll again
   //postcondition of loop: we have a number uniformly at random between 0 and 20
return r % 7 + 1;
//there are 3 numbers in [0, 20] for each possible return value
//so each has equal probability.
}
POST YOUR OPINION IF YOU HAVE BETTER SOLUTION

No comments:

Post a Comment

Your feedback is always appreciated.
I will try to reply to your queries as soon as time allows.
Please do not spam Spam comments will be deleted immediately upon our review.