470. Implement Rand10() Using Rand7()
Description
Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.
Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().
Example 1:
Input: n = 1 Output: [2]
Example 2:
Input: n = 2 Output: [2,8]
Example 3:
Input: n = 3 Output: [3,8,10]
Constraints:
1 <= n <= 105
Follow up:
- What is the expected value for the number of calls to
rand7()function? - Could you minimize the number of calls to
rand7()?
Solutions
Solution 1
Thinking
We must turn uniform \(rand7\) into uniform \(rand10\). \(\textit{rand7}\bmod 10\) is biased. Two calls give a uniform integer in \([1,49]\).
Rejection sampling keeps \([1,40]\) and returns \(x\bmod 10+1\); values \(41\)–\(49\) retry. \(40\) is a multiple of \(10\), so each residue appears four times.
The expected number of calls is constant. Rejecting the tail is what keeps every outcome equally likely.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |