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.

 

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()?
class Solution extends SolBase {
    public int rand10() {
        int i,j;
        while( (i = rand7()) > 6);  // P(i is even) = P(i is odd) = 0.5
        while( (j = rand7()) > 5);  // P(j==1) = P(j==2) = P(j==3) = P(j==4) = P(j==5) = 0.2
        return i % 2 == 0 ? j : j + 5;
    }
}

阴间方法??居然是brain teaser

想一下要random get 1-10,给的条件只有random get 1-7,怎么办?

上面的方法是平等的拿到奇偶数(如果i是7就继续循环,反正得到1-6就可以了,而123456奇偶概率相等),然后再平等的拿到1-5(如果j是6,7就循环,直到得到12345(概率相等)就停止),然后如果even和odd各返回1-5 和 6-10 屮

posted @ 2020-08-29 01:37  Schwifty  阅读(191)  评论(0)    收藏  举报