Yekun's Note

Machine learning notes and writeup.

Fork me on GitHub

LeetCode practice: random

Leetcode practice of the random topic.

Leetcode 470. Implement Rand10() Using Rand7()

Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.
Do NOT use system’s Math.random().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7

class Solution(object):
def rand10(self):
"""
:rtype: int
"""
# the maximum common multiple n*10 (n=4) that is less than 49 (7*7)
       reject_threshold = 40
# threshold <= res <= 7*7, to enter the following loop
       res = 41
       while res > reject_threshold:
res = (rand7()-1)*7 + rand7() # generate 0 - 7*7
return res%10 + 1