Given a function rand7()
that generates a uniform random integer in the range of [1, 7], write a function rand10()
that generates a uniform random integer in the range of [1, 10].
rand7()
can be called?
rand7()
guaranteed to be perfectly uniform?
rand7()
produces each integer in the range [1, 7] with equal probability.rand7()
?
rand7()
is already implemented and available for use.To generate a uniform random number within [1, 10] using rand7()
, we can use the following strategy:
rand7()
. Think of it as generating a two-digit number in base 7.rand7()
to generate a number in the range [1, 49] (i.e., rand7() - 1
gives us 0 to 6 which can be used simulating digits in base 7).This approach ensures uniformity because each of the numbers from 1 to 49 has an equal chance, and we uniformly map a subset of this range to our desired [1, 10].
import random
def rand7():
return random.randint(1, 7)
def rand10():
while True:
num1 = rand7() - 1 # range 0 to 6
num2 = rand7() - 1 # range 0 to 6
combined = num1 * 7 + num2 # range 0 to 48
# Only use the result if it's within 0 to 39
if combined < 40:
return (combined % 10) + 1 # range 1 to 10
# Testing rand10 function
from collections import Counter
results = [rand10() for _ in range(10000)]
counter = Counter(results)
print("Distribution of results in 10000 trials:")
for i in range(1, 11):
print(f"{i}: {counter[i]}")
The expected time complexity is O(1), though the actual time may vary since we keep retrying until we get a number within the acceptable range. The probability of needing retries is slight, so this remains efficient in practice.
rand7()
call is O(1).Overall, the solution provides a uniform random distribution in the range [1, 10] efficiently with an expected constant time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?