2014-04-29 00:00

题目:给定一个rand5()函数,能够返回0~4间的随机整数。要求实现rand7(),返回0~6之间的随机整数。该函数产生随机数必须概率相等。

解法:自己想了半天没想出等概率的方法,最后参考答案了。答案思想实在巧妙:随机0~24间的数,然后把21~24丢弃,剩余的0~20对7取模就是等概率随机数了。

代码:

 1 // 17.11 Given a rand5() method, which generates random integer between [0, 4]. Please implement rand7() for [0, 6].
 2 // The key to this problem, is to make sure every number gets the same probability.
 3 #include <cstdio>
 4 #include <cstdlib>
 5 using namespace std;
 6 
 7 int rand5()
 8 {
 9     return rand() % 5;
10 }
11 
12 int rand7()
13 {
14     int val;
15     
16     while (true) {
17         val = 5 * rand5() + rand5();
18         if (val < 21) {
19             return val % 7;
20         }
21     }
22 }
23 
24 int main()
25 {
26     while (true) {
27         printf("%d\n", rand7());
28     }
29     
30     return 0;
31 }

 

 posted on 2014-04-29 00:04  zhuli19901106  阅读(171)  评论(0编辑  收藏  举报