On Sep 7, 11:56 am, ankur aggarwal <ankur.mast....@gmail.com> wrote:
>   Given a random number generator that generates numbers in the range 1 to
> 5, how can u create a random number generator to generate numbers in the
> range 1 to 7. (remember that the generated random numbers should follow a
> uniform distribution in the corresponding range)

If you generate 2 random numbers, there are 25 possible outcomes.
This doesn't map nicely to the 7 desired outcomes.  The standard way
out of this mess is to ignore 4 outcomes leaving 21.  Then map these
to the range 1 to 7:

int n;
do n = (random1to5() - 1) * 5 + (random1to5() - 1); while n >= 7 * 3;
return 1 + n % 7

You can avoid throwing away random numbers with higher probabilty by
generating more to begin with.

For example, generating 3 provides 5 * 5 * 5 = 125 possible outcomes.
Discard 6 cases to leave 119 = 17 * 7.  So we have

int n;
do n = (random1to5() - 1) * 5 * 5  + (random1to5() - 1) * 5 +
(random1to5() - 1); while n >= 7 * 17;
return 1 + n % 7

The probability of discarding a number is 4/25 in the first case, but
only 6 / 125 in the second.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/algogeeks
-~----------~----~----~----~------~----~------~--~---

Reply via email to