read
Question:
Lets have a rand5 function, that returns values from 0 to 4. Each value is given with probability 1 in 5. Use this function to define rand7, that returns values 0 to 6 (each value is given with probability 1 in 7).
Solution:
There are more ways to solve this. Here is one:
- Multiply the first rand5 value by five and add the second rand5 result.
x = 5*rand5 + rand5.
- x contains random value from 0 to 24 - all values with equal probability.
- Calculate the x formula in a while cycle until the x value is from 0 to 6. That is your result.
Additional questions
What is the maximum runtime of this algorithm ?
Is there any way to improve the chance of getting the right numbers?