Simulate random7() using random5() - PrismoSkills
Puzzle: Given a function random5() which randomly generates numbers from 1 to 5 with equal probability, writea function random7() which generates numbers from 1 to 7 with equal probability.
Solution: Probability of any number being generated by random5() = 1/5 = 0.2
Probability of any number being generated by random7() = 1/7 = 0.14
How about random7() = 1 + (random5() + random5()) % 7
It generates numbers from 1 to 7, so functionally it's correct.
However, the numbers are not generated by equal probability.
Here is the probability of each number being generated.
Total number of ways = 5*5 = 25 (because each random() can generate any number from 1 to 5)
Read full article from Simulate random7() using random5() - PrismoSkills
No comments:
Post a Comment