您的位置:首页 > 其它

[CareerCup] 17.11 Rand7 and Rand5 随机生成数字

2016-04-27 12:24 211 查看
17.11 Implement a method rand7() given rand5(). That is, given a method that generates a random number between 0 and 4 (inclusive), write a method that generates a random number between 0 and 6 (inclusive).

这道题说给了我们一个rand5()函数,可以生成0到4之间的随机数,让我们写一个函数rand7()可以生成0到6之间的随机数,那么我们写出来的这个rand7()函数必须生成0到6之间每个数字的概率为1/7。那么我们首先想能不能用(rand5()+rand5())%7来做,答案是不行的,我们来看一下rand5()+rand5()中每个数字出现的概率:

0 (1/25)

1 (2/25)

2 (3/25)

3 (4/25)

4 (5/25)

5 (4/25)

6 (3/25)

7 (2/25)

8 (1/25)

而我们需要的rand7()是要0到6中每个数的出现概率是1/7才行,所以我们必须生成一个区间,每个数字的出现概率是相同的。那么我们可以用5*rand5()+rand5(),这生成了[0, 24]区间中的25个数字,每个数字的出现概率都是1/25,那么我们只要当随机生成的数字小于21,对7取余返回即可:

解法一:

int rand7() {
while (true) {
int num = 5 * rand5() + rand5();
if (num < 21) {
return num % 7;
}
}
}


其实我们也可以用2*rand5()来生成等概率区间,就是稍微麻烦一些,因为rand5()*2等概率的生成0,2,4,6,8,所以我们需要构造一个等概率生成0,1,和rand5()*2相加就是等概率生成[0,9]区间的数,参见代码如下:

解法二:

int rand7() {
while (true) {
int r1 = rand5() * 2;
int r2 = rand5();
if (r2 != 4) {
int num = r1 + r2 % 2;
if (num < 7) {
return num;
}
}
}
}


CareerCup All in One 题目汇总
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: