[LeetCode] 470. Implement Rand10() Using Rand7()


Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.

Do NOT use system's Math.random().

 

Example 1:

Input: 1
Output: [7]
Example 2:

Input: 2
Output: [8,4]
Example 3:

Input: 3
Output: [8,1,10]

Note:

rand7 is predefined.
Each testcase has one argument: n, the number of times that rand10 is called.

Follow up:

What is the expected value for the number of calls to rand7() function?
Could you minimize the number of calls to rand7()?
题意:用一个可以随机生成1-7 的rand7() 做一个随机生成 1-10的rand10()

随机生成的数只有整数,要得到随机的10,就得想办法去搞到一个10的倍数的随机数集

10的倍数的数字必须每个数都出现

7的倍数往上走就会出现

{1,2,....,7}

{2,4,....,14}

{3,6,....,21}

......等等类似的序列,这些序列的特点就是中间会产生差值,rand7()会生成1-7的随机数

比方说 1+ rand7() 就不会产生1,

{7,14,...,49}因为必须要有前面的数字,那么,我们改为

{0,6,12,...,42},然后我们把每个数字加0-6,也就是rand7() - 1,就可以随机的得到0-48;

回到开头,我们需要满足某个10的整数倍内产生的 数是随机的,0-48是随机产生的,等概率

那么 0-39 这四十个数字出现概率是等概率的,我们舍弃40-48的数字,并不会产生影响,因为我们产生的其他数字是等概率的,我们只要那40个数字

最后由于0-39 对10取余没办法产生10,那么对其+1即可

class Solution extends SolBase {
    public int rand10() {
        int res = 40;
        while (res >= 40) {
            res = 7*(rand7()-1) + (rand7() - 1);
        }
        return res%10 + 1;
    }
}

 

posted @ 2018-09-16 09:14  C`Moriarty  阅读(89)  评论(0编辑  收藏  举报
/* 鼠标点击求赞文字特效 */ /*鼠标跟随效果*/