The title
The existing method RAND7 can generate uniform random integers in the range of 1 to 7. Try writing a method RAND10 to generate uniform random integers in the range of 1 to 10.
Do not use the system’s math.random () method.
Example 1: input: 1 output: [7] example 2: input: 2 output: [8,4] example 3: input: 3 output: [8,1,10]Copy the code
Tip:
Rand7 is defined. The passed argument: n represents the number of calls to RAND10.
Advanced:
What is the expected number of calls to RAND7 ()? Can you call RAND7 () as little as possible?
Their thinking
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
while True:
row = rand7()
col = rand7()
idx = (row - 1) * 7 + col
if idx <= 40:
return 1 + (idx - 1) % 10
Copy the code