1. Int rand7 ()
2 .{
3. Return rand () % 7 + 1;
4 .}
5.
6. Int rand10 ()
7 .{
8. Int x = 0;
9. Do
10 .{
11. x = (rand7 ()-1) * 7 + rand7 ();
12 .}
13. While (x> 40 );
14. Return X % 10 + 1;
15 .}
Analysis: To ensure the even distribution of rand10 () on integers 1-10, you can construct a random integer interval with a 1-10 * n uniform distribution (N is any positive integer ). Assume that X is a random integer in the range of 1-10 * n. Then, X % 10 + 1 is an integer evenly distributed between 1 and 10. Because (rand7 ()-1) * 7 + rand7 () can construct a random number evenly distributed between 1 and 49 (for the reason, see the following description), you can set ~ If such a random number is removed, 1-40 is still evenly distributed among 1-40, because each number can be considered as an independent event.
The following explains why (rand7 ()-1) * 7 + rand7 () can create a random number evenly distributed between 1 and 49:
First, rand7 ()-1 gets a discrete integer set {0, 1, 2, 3, 4, 5, 6}, where each integer has a probability of 1/7. Then (rand7 ()-1) * 7 gets a discrete Integer Set A = {1/7, 42}, where each integer has a probability. The probability of each integer in the Set B = {1, 2, 3, 4, 5, 6, 7} obtained by rand7 () is also 1/7. Obviously, the combination of any two elements in A and B can correspond One to One integer between 1 and 49, that is, any number between 1 and 49, A combination of two elements in A and B can be uniquely identified. Since elements A and B can be considered as independent events, according to the probability formula p (AB) = P (a) P (B) of independent events ), the probability of each combination is 1/7*1/7 = 1/49. Therefore, the integers (rand7 ()-1) * 7 + rand7 () are evenly distributed between 1 and 49, and the probability of each number is 1/49.