int rand7() { return rand()%7+1; } int rand10(){ int x=0; do { x=(rand7()-1)*7+rand7(); } while(x>40); return x%10+1;}
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. So(Rand7 ()-1) * 7 get a discrete Integer Set A = {, 35, 42}The probability of occurrence of each integer is also 1/7. WhileThe 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 unique combination of two elements in A and B.. 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.
PS: use while (x> 40) instead of while (x> 10? The reason is that if you use while (x> 10), there is a 40/49 probability that you need to loop while, and it is very likely that there is an endless loop.
From: http://blog.csdn.net/furturerock/article/details/6850634