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
INPUTrand7() Range1234567Each value has1/7 probabilityNeed: [1,10]uniform distributionALGORITHMRejection Sampling1Call rand7() twice2Generate [1,49] range3Accept [1,40] only4Map to [1,10] evenlyAccept Zone: [1,40]Maps to [1,10]4 occurrences eachReject: [41,49] → retryRESULTUniform rand10()12345678910Each value hasexactly 10%probabilityPerfect UniformityKey Insight:Rejection sampling preserves uniform distribution by discardingoutcomes that would create bias, ensuring mathematical correctness.TutorialsPoint - Implement Rand10() Using Rand7() | Rejection Sampling
Asked in
Google 15 Facebook 12 Microsoft 8 Amazon 6
78.4K Views
Medium Frequency
~15 min Avg. Time
987 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