admin管理员组

文章数量:1637231

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部分,总概率 =

程序如下所示:

/**
 * 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;
            }
        }
    }
}

 

本文标签: implement