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:

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

Follow up:

  1. What is the expected value for the number of calls to rand7() function?
  2. Could you minimize the number of calls to rand7()?

这道题给了我们一个随机生成 [1, 7] 内数字的函数 rand7(),需要利用其来生成一个能随机生成 [1, 10] 内数字的函数 rand10(),注意这里的随机生成的意思是等概率生成范围内的数字。这是一道很有意思的题目,由于 rand7() 只能生成1到7之间的数字,所以 8,9,10 这三个没法生成,那么怎么办?大多数人可能第一个想法就是,再用一个呗,然后把两次的结果加起来,范围不就扩大了么,扩大成了 [2, 14] 之间,然后如果再减去1,范围不就是 [1, 13] 了么。想法不错,但是有个问题,这个范围内的每个数字生成的概率不是都相等的,为啥这么说呢,我们来举个简单的例子看下,就比如说 rand2(),我们知道其可以生成两个数字1和2,且每个的概率都是 1/2。那么对于 (rand2() - 1) + rand2()呢,看一下:

rand2() -  + rand()  =   ?

我们发现,生成数字范围 [1, 3] 之间的数字并不是等概率大,其中2出现的概率为 1/2,1和3分别为 1/4。这就不随机了。问题出在哪里了呢,如果直接相加,不同组合可能会产生相同的数字,比如 1+2 和 2+1 都是3。所以需要给第一个 rand2() 升一个维度,让其乘上一个数字,再相加。比如对于 (rand2() - 1) * 2 + rand2(),如下:

(rand2() - ) *  + rand()  =   ?

这时右边生成的 1,2,3,4 就是等概率出现的了。这样就通过使用 rand2(),来生成 rand4()了。那么反过来想一下,可以通过 rand4() 来生成 rand2(),其实更加简单,我们只需通过 rand4() % 2 + 1 即可,如下:

rand4() %  +  =  ?

同理,我们也可以通过 rand6() 来生成 rand2(),我们只需通过 rand6() % 2 + 1 即可,如下:

 rand6() %  +  =  ?

所以,回到这道题,我们可以先凑出 rand10*N(),然后再通过 rand10*N() % 10 + 1 来获得 rand10()。那么,只需要将 rand7() 转化为 rand10*N() 即可,根据前面的讲解,我们转化也必须要保持等概率,那么就可以变化为 (rand7() - 1) * 7 + rand7(),就转为了 rand49()。但是 49 不是 10 的倍数,不过 49 包括好几个 10 的倍数,比如 40,30,20,10 等。这里,我们需要把 rand49() 转为 rand40(),需要用到 拒绝采样 Rejection Sampling,总感觉名字很奇怪,之前都没有听说过这个采样方法,刷题也是个不停学习新东西的过程呢。简单来说,这种采样方法就是随机到需要的数字就接受,不是需要的就拒绝,并重新采样,这样还能保持等概率,具体的证明这里就不讲解了,博主也不会,有兴趣的童鞋们可以去 Google 一下~ 这里直接用结论就好啦,当用  rand49() 生成一个 [1, 49] 范围内的随机数,如果其在 [1, 40] 范围内,我们就将其转为 rand10() 范围内的数字,直接对 10 去余并加1,返回即可。如果不是,则继续循环即可,参见代码如下:

解法一:

class Solution {
public:
int rand10() {
while (true) {
int num = (rand7() - ) * + rand7();
if (num <= ) return num % + ;
}
}
};

我们可以不用 while 循环,而采用调用递归函数,从而两行就搞定,叼不叼~

解法二:

class Solution {
public:
int rand10() {
int num = (rand7() - ) * + rand7();
return (num <= ) ? (num % + ) : rand10();
}
};

我们还可以对上面的解法进行一下优化,因为说实话在 [1, 49] 的范围内随机到 [41, 49] 内的数字概率还是挺高的,我们可以做进一步的处理,就是当循环到这九个数字的时候,我们不重新采样,而是做进一步的处理,将采样到的数字减去 40,这样就相当于有了个 rand9(),那么通过 (rand9() - 1) * 7 + rand7(),可以变成 rand63(),对 rand63() 进行拒绝采样,得到 rand60(),从而又可以得到 rand10()了,此时还会多余出3个数字,[61, 63],通过减去 60,得到 rand3(),再通过变换 (rand3() - 1) * 7 + rand7() 得到 rand21(),此时再次调用拒绝采样,得到 rand20(),进而得到 rand10(),此时就只多余出一个 21,重复整个循环的概率就变的很小了,参见代码如下:

解法三:

class Solution {
public:
int rand10() {
while (true) {
int a = rand7(), b = rand7();
int num = (a - ) * + b;
if (num <= ) return num % + ;
a = num - , b = rand7();
num = (a - ) * + b;
if (num <= ) return num % + ;
a = num - , b = rand7();
num = (a - ) * + b;
if (num <= ) return num % + ;
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/470

类似题目:

Generate Random Point in a Circle

参考资料:

https://leetcode.com/problems/implement-rand10-using-rand7/

https://leetcode.com/problems/implement-rand10-using-rand7/discuss/152282/C%2B%2B-2-line

https://leetcode.com/problems/implement-rand10-using-rand7/discuss/175450/Java-Solution-explain-this-problem-with-2D-matrix

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Implement Rand10() Using Rand7() 使用Rand7()来实现Rand10()的更多相关文章

  1. [LeetCode] Implement Queue using Stacks 用栈来实现队列

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

  2. [LeetCode] Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  3. [LeetCode] Implement Trie (Prefix Tree) 实现字典树(前缀树)

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  4. [LeetCode] Implement strStr() 实现strStr()函数

    Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...

  5. [Leetcode] implement strStr() (C++)

    Github leetcode 我的解题仓库   https://github.com/interviewcoder/leetcode 题目: Implement strStr(). Returns ...

  6. [LeetCode] Implement Magic Dictionary 实现神奇字典

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  7. LeetCode - Implement Magic Dictionary

    Implement a magic directory with buildDict, and search methods. For the method buildDict, you'll be ...

  8. LeetCode Implement strStr()(Sunday算法)

    LeetCode解题之Implement strStr() 原题 实现字符串子串匹配函数strStr(). 假设字符串A是字符串B的子串.则返回A在B中首次出现的地址.否则返回-1. 注意点: - 空 ...

  9. Leetcode Implement Queue using Stacks

    Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of ...

随机推荐

  1. JAVA实现C/S结构小程序

    程序功能: 客户端向服务器发送一个本地磁盘中的文件, 服务器程序接受后保存在其他位置. 客户端实现步骤: 创建一个客户端对象Socket,构造方法中绑定服务器的IP地址 和 端口号 使用Socket对 ...

  2. 五十二、linux 编程——网络介绍

    52.1 网络介绍 使用远程资源 共享信息.程序和数据 分布处理 52.1.1 协议的概念 计算机网络中实现通信必须有一些约定,如对速率.传输代码.代码结构.传输控制步骤和出错控制等约定,这些约定即被 ...

  3. [译]Ocelot - Configuration

    原文 这里有一个配置的样例.配置主要有两个部分.一个是ReRoutes数组,另一个是GlobalConfiguration.ReRoute告诉Ocelot怎么处理上游的请求.Global config ...

  4. python学习03

    字符串的基本使用 1.字符编码集 ASCII编码:外国人常用的大小写英文字母.数字和一些符号,一共127个字符,用1个字节(byte)可以涵盖完,也就是8个位,它将序列中的每个字节理解为一个字符. U ...

  5. What a Ridiculous Election UVALive - 7672 (BFS)

    题目链接: E - What a Ridiculous Election  UVALive - 7672 题目大意: 12345 可以经过若干次操作转换为其它五位数. 操作分三种,分别为: 操作1:交 ...

  6. 个人经验~ 利用5.7的sys库更好的排查问题

    一 简介:今天我们讲讲如何利用5.7的sys新库进行问题的排查二 描述   1 Sys库所有的数据源来自:performance_schema和information_schema.目标是把perfo ...

  7. NB卡开卡注意事项【转】

    转自:https://blog.csdn.net/cheng401733277/article/details/83276436 版权声明:本文为博主原创文章,未经博主允许不得转载. https:// ...

  8. .Net IOC框架入门之三 Autofac

    一.简介   Autofac是.NET领域最为流行的IOC框架之一,传说是速度最快的一个 目的 1.依赖注入的目的是为了解耦. 2.不依赖于具体类,而依赖抽象类或者接口,这叫依赖倒置. 3.控制反转即 ...

  9. 转 -Filebeat + Redis 管理 LOG日志实践

    Filebeat + Redis 管理 LOG日志实践 小赵营 关注 2019.01.06 17:52* 字数 1648 阅读 24评论 0喜欢 2 引用 转载 请注明出处 某早上,领导怒吼声远远传来 ...

  10. centos 搭建 leanote

    centos 搭建leanote(蚂蚁笔记) 至于蚂蚁笔记是什么可以看官网的介绍,https://leanote.com/  ,我只能说 nice,你值得拥有. 开始搭建(源码安装,安装路径在 /et ...