Leetcode Problem 470. Implement Rand10() Using Rand7()

470. Implement Rand10() Using Rand7()

Leetcode Solutions

Rejection Sampling

  1. Call rand7() and store the result in row, giving us a number from 1 to 7.
  2. Call rand7() again and store the result in col, giving us another number from 1 to 7.
  3. Calculate idx = (row - 1) * 7 + col, which gives us a number from 1 to 49.
  4. If idx is less than or equal to 40, return idx % 10 + 1 to get a number from 1 to 10.
  5. If idx is greater than 40, reject it and go back to step 1.
UML Thumbnail

Utilizing out-of-range samples

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...