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
Transform rand7() → rand10() Using Rejection SamplingInput: rand7()1234567Process: Rejection SamplingTwo rand7() calls → 1-49 range → Keep 1-40 → Map to 1-10num = (rand7()-1)*7 + rand7()if num ≤ 40: return (num-1)%10+1else: retryOutput: rand10()12345678910Why Rejection Sampling WorksPreserves UniformityEach Output Equally LikelyRange 1-40 maps to 1-10 with each number appearing exactly 4 timesRange 41-49 is rejected to maintain equal probability for all outputsExpected 1.4 calls to rand7() per rand10() call
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
Asked in
Facebook 15 Google 12 Apple 8
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen