1. Question
Given a random number generator, this generator can generate a random number ranging from 1 to 5 () evenly. How can we use this generator to generate a number ranging from 1 to 7?
2. Ideas
Method 1: generate two (1, 5) random numbers. In this case, there are 25 random numbers. Note that these two numbers are sequential. In these 25 cases, take the first 21 random numbers, each three represents a number in (). If you get a number other than these 21 types, you can discard them.
Method 2: generate three () random numbers, representing a binary bit, where 1 and 2 map to 0, 3 Skip, 4 and 5 map to 1. The resulting three-digit binary number, that is, the 8 numbers 1-8 are of equal probability. If 8 is generated, discard it.
Method 3: generate two (1, 5) random numbers, and generate a binary number, 5*(random5 ()-1) + random5 (). This formula can produce 1-25 equi-probability, that is, the first random number represents:, 20, and the position represents 1, 2, 3, 4, 5. In this way, this number (a number ranging from 1 to 25) is discarded by using the method 1 with only 1-21 and 7 points, representing 1-7, 22-25.
3. Reference
Generate a random number within () according to the random number generator ().
[Beauty of programming] Summary of random number range extension methods