随笔- 509  文章- 0  评论- 151  阅读- 22万 

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   zhuli19901106  阅读(173)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示