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:

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

已知Rand7,求Rand10。

思路:

根据Rand7,求得0~10n-1的随机数,包含0,不包含10*n - 1,假设当前求得0~10*n-1中的随机数为m,则m%10即为0~9中的随机数,m%10 + 1即为1~10中的随机数,即为所求。

7*(Rand7() - 1) = {0, 7, 14, 21, 28, 35, 42},这7个数等概率

7*(Rand7() - 1) + Rand() - 1表示{0,1,2,3,4,5,6,......40, ... 48},这49个数等概率

再将这49个数分为两部分, {0, 1, 2, ... , 39}和{40, 41, .., 48},如果生成的数处于第2部分,再将第二部分等概率分到第1部分,总概率 = p = \frac{\frac{40}{49}*\frac{1}{40}}{\frac{40}{49}*\frac{1}{40} + \frac{9}{49}} = \frac{1}{10}

程序如下所示:

/**
 * The rand7() API is already defined in the parent class SolBase.
 * public int rand7();
 * @return a random integer in the range 1 to 7
 */
class Solution extends SolBase {
    public int rand10() {
        int num = 0;
        while (true){
            num = 7*(rand7() - 1) + rand7() - 1;
            if (num < 40){
                return (num%10) + 1;
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值