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].
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().
Input & Output
Example 1 — Basic Execution
$
Input:
Call rand10() once
›
Output:
7
💡 Note:
rand7() returns 3 and 4, giving (3-1)*7+4=18. Since 18 ≤ 40, return (18-1)%10+1 = 8. Note: actual output is random, this shows the process.
Example 2 — Rejection Case
$
Input:
Call rand10() once
›
Output:
2
💡 Note:
First: rand7() returns 6,7 giving 42 > 40, reject. Second: rand7() returns 1,3 giving 3, return (3-1)%10+1 = 3. Shows rejection sampling in action.
Example 3 — Distribution Check
$
Input:
Call rand10() 1000 times
›
Output:
Each number 1-10 appears roughly 100 times
💡 Note:
Over many calls, each output from 1 to 10 should appear with equal probability (~10%), demonstrating uniform distribution.
Constraints
- You must only use the given rand7() API
- Do not use any other random number generator
- The output must be uniformly distributed over [1, 10]
- Each call to rand10() should be independent
Visualization
Tap to expand
Understanding the Visualization
1
Input
rand7() API generating uniform integers 1-7
2
Transform
Use rejection sampling to create uniform 1-10 distribution
3
Output
rand10() function returning uniform integers 1-10
Key Takeaway
🎯 Key Insight: Use rejection sampling to transform distributions while preserving uniformity
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code