2014-04-29 00:00

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

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

代码:

 // 17.11 Given a rand5() method, which generates random integer between [0, 4]. Please implement rand7() for [0, 6].
// The key to this problem, is to make sure every number gets the same probability.
#include <cstdio>
#include <cstdlib>
using namespace std; int rand5()
{
return rand() % ;
} int rand7()
{
int val; while (true) {
val = * rand5() + rand5();
if (val < ) {
return val % ;
}
}
} int main()
{
while (true) {
printf("%d\n", rand7());
} return ;
}
05-26 17:49