Implement Rand10() Using Rand7() - Problem
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].
Requirements:
- You can only call the API
rand7() - 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().
Input & Output
Example 1 — Generate 5 random numbers
$
Input:
n = 5
›
Output:
[7,2,10,3,8]
💡 Note:
Function is called 5 times, each call returns a uniform random integer in [1,10]. Actual output will vary since it's random.
Example 2 — Generate 3 random numbers
$
Input:
n = 3
›
Output:
[1,9,4]
💡 Note:
Three independent calls to rand10(), each producing a value between 1 and 10 inclusive with equal probability.
Example 3 — Single call
$
Input:
n = 1
›
Output:
[6]
💡 Note:
Single call returns one random value. All values 1-10 have equal 10% probability.
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()?
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code