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


    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 题目汇总

  • 相关阅读:
    Python 编码问题(十四)
    Python 编程核心知识体系-文件对象|错误处理(四)
    Python 编程核心知识体系-模块|面向对象编程(三)
    项目中的走查
    回滚代码及pod install报错
    UI-3
    UI-2
    UI-1
    MarkDown基本语法速记
    Swift3.0-closure的@autoclosure和@escaping
  • 原文地址:https://www.cnblogs.com/grandyang/p/5438403.html
Copyright © 2020-2023  润新知