
The objective is to implement a function rand10() that generates a uniform random integer in the range [1, 10] using only an existing function rand7(). rand7() is a given API which uniformly generates a random integer between 1 and 7. The solution must rely solely on rand7() for generating randomness and is prohibited from using any built-in random functions from your programming language.
Each test case implicitly contains a parameter n, which represents how many times the rand10() function will be executed during testing. This parameter is used internally and is not explicitly passed to the rand10() function itself.
Input:
Output:
Input:
Output:
Input:
Output:
1 <= n <= 105Recognize that rand7() gives a random integer between 1 and 7, but we need an evenly distributed way to extend this range to 1-10. Note that there are more combinations possible when using the range of 1-7 compared to 1-10.
Leverage these multiple outputs from rand7() to cover a range larger than 10. One practical approach is to think in terms of a 2-dimensional matrix or a base conversion:
rand7() to determine the row and another rand7() to determine the column, we can map the 49 outcomes to our desired range of 1-10.Understanding that 49 outcomes cannot be evenly distributed into 10 groups, some adjustment is needed:
Implement:
num1, from rand7().num2, from rand7().(num1 - 1) * 7 + num2. This value now lies in [1, 49].This method should guarantee a uniform distribution as long as the re-roll probability and mapping are carefully balanced, ensuring every number from 1 to 10 in rand10() has an equal chance of 1/10.
The solution provided outlines an implementation of the generateRandom10() function using the predefined rand7() function. This method effectively transforms a uniform random integer generator that produces numbers from 1 to 7 (rand7) into one that produces numbers from 1 to 10 (rand10).
rand7(). This part is achieved by:step1) and scaling its zero-based version up by multiplying by 7, then adding another random number (step2).This technique guarantees that the distribution of the output numbers is uniform despite starting from a smaller range and dealing with the challenge of rejection in intermediate steps. The use of such statistical methods allows for the efficient use of the random resource (rand7()) while ensuring the desired outcome range and uniform distribution.
0 Comments
Be the first to comment and share your perspective with the community.