Implement Rand10 Using Rand7
To solve this coding challenge, we'll leverage the existing
API, which provides a uniform random integer from 1 to 7, in order to create a new function
that outputs a uniform random integer from 1 to 10. The key challenge here is converting the output range of a uniform random number generator efficiently without introducing significant bias.
is equally probable.
rand7()
rand10()
Explanation
Here's an in-depth explanation of the methodology we'll employ:-
Understanding rand7() Output
: The
rand7()
-
Expanding the Range Multiplicatively
: By calling
rand7()
-
The first call to
rand7()
-
The second call to
rand7()
- Mapping 49 Outcomes to a Useful Range : Since we want a range from 1 to 10:
- Generate a number between 1 and 49. Each of these 49 outcomes should have equal probability.
- Use only the first 40 outcomes and map them evenly to 1-10. The remaining 9 outcomes (41-49) are discarded, and we repeat the process until we get a valid number within 1-40.
- Dividing and Modulo Operation : By leveraging modulo operations, we can map the 40 outcomes to the desired range of 1-10.
- Generate Extended Range :
-
(rand7() - 1) * 7 + rand7()
-
rand7() - 1
-
Adding another
rand7()
- Discard Unfit Values :
-
The condition
if num <= 40
-
If
num
- Modulo and Offset :
-
num % 10
- Initiate Loop :
- Continue until a valid number (within 1-40) is found.
- First randomized number :
-
(rand7() - 1) * 7
- Second randomized number :
-
Add a second
rand7()
- Check Validity :
- Confirm if within 1-40. If not, repeat.
- Return Mapped Result :
- Use modulo operation and adjust range to return a number between 1 and 10.
-
To fully utilize these results, we think of the first call as choosing a row and the second call as choosing a column in a 7x7 grid, creating a total of 49 possible outcomes (7*7).
Pseudocode with Comments
The pseudocode below describes the detailed steps to solve this problem:
function rand10():
while True:
# Generate a number in the range [1, 49]
num = (rand7() - 1) * 7 + rand7()
# If the number lies within the first 40 outcomes, map it to [1, 10]
if num <= 40:
return num % 10 + 1
# If the number is outside [1, 40], discard and repeat
The pseudocode efficiently maps the outputs of
rand7()
Detailed Steps in Pseudocode
rand10()