zoukankan      html  css  js  c++  java
  • [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 题目汇总

  • 相关阅读:
    openstack常见问题
    30 个 Openstack 经典面试问题和解答
    linux系统内存爆满的解决办法!~
    iostat详解
    线上应用故障排查之一:高CPU占用
    对OpenStack运维架构的总结(转)
    zabbix基本监控各指标简解
    创建 OpenStack云主机
    centos7系统中忘记了root管理员账号密码的解决方式(转)
    MySQL高可用架构之MHA
  • 原文地址:https://www.cnblogs.com/grandyang/p/5438403.html
Copyright © 2011-2022 走看看