Problem Description
Given an API rand7() that returns a uniform random integer in the range [1, 7], implement a function rand10() that returns a uniform random integer in the range [1, 10] using only calls to rand7().
Key Insights
- The problem can be solved using rejection sampling.
- By combining two calls to rand7(), we can generate a uniform integer in the range [1, 49].
- If the generated number is between 1 and 40, it can be mapped to the range [1, 10] uniformly.
- If the number falls in the range [41, 49], it is discarded and the process is repeated.
- This method guarantees uniform distribution for rand10().
Space and Time Complexity
Time Complexity: Expected O(1) per call (with a constant expected number of iterations due to rejection sampling)
Space Complexity: O(1)
Solution
The solution involves using rejection sampling:
- Generate a number in the range [1, 49] by combining two rand7() calls: calculate num = (rand7() - 1) * 7 + rand7().
- If num is less than or equal to 40, use (num - 1) % 10 + 1 to convert it into a number in the range [1, 10].
- If num is greater than 40, reject the number and repeat the process. This approach uses rejection sampling to ensure that each number in the range [1, 10] is equally likely.