Problem

Implement Rand10() Using Rand7()

Approach

We can use two variables, i & j, generated by Rand7() to get one new number. Then, we can get the followed matrix.

  1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 8 9 10 11 12 13 14
3 15 16 17 18 19 20 21
4 22 23 24 25 26 27 28
5 29 30 31 32 33 34 35
6 36 37 38 39 40 41 42
7 43 44 45 46 47 48 49

In the matrix, numbers from 41 to 49 should be discarded. And these left numbers can be used to generated new nubmers from 1 to 10.

Code

/**
 * 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() {
        while(true){
            int i = rand7(), j = rand7();
            int sum = (i - 1) * 7 + j;
            if(sum >= 41) continue;
            sum = sum % 10;
            if(sum == 0){
                sum = 10;
            }
            return sum;
        }
    }
}