zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    echarts官网上的动态加载数据bug被我解决。咳咳/。
    jquery中的jsonp和js中的jsonp还有配合php实现的jsonp。
    jquery中的done和always解决ajax问题
    vue2.0使用watch监听对象属性
    gulp配合vue压缩代码格式化
    支持flv的播放神器
    前端组件化-Web Components【转】
    自定义异步加载资源插件
    【leetcode刷题笔记】Two Sum
    【leetcode刷题笔记】Longest Common Prefix
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9655067.html
Copyright © 2011-2022 走看看