已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
不要使用系统的 Math.random() 方法。
示例 1:
输入: 1
输出: [7]
示例 2:
输入: 2
输出: [8,4]
示例 3:
输入: 3
输出: [8,1,10]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-rand10-using-rand7
方法1 - 失败 - 部分数字得不到
# 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
"""
return int( rand7()/7*10)
直接粗暴矩阵导致部分数组无法得到 : 如 9
方法2 - 失败 - 生成的随机数不均匀
class Solution:
def rand10(self) -> int:
return rand7()+rand7()//2
tips
- 概率不均匀,比如 1 只能是 1 + 1 / 2 生成,2 却可以通过 1 + 2 / 2,1 + 3 / 2,2 + 1 / 2 生成。
方法3- 官方题解 - 通过
class Solution:
def rand10(self) -> int:
while True:
row = rand7()
col = rand7()
idx = (row - 1) * 7 + col
if idx <= 40:
return 1 + (idx - 1) % 10
方法4 - 通过 - 在官方题解基础上,使拒绝采样的区域尽可能小
基于一个事实 (randX() - 1)*Y + randY() 可以等概率的生成[1, X * Y]范围的随机数
参考题解:
# 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) -> int:
while True:
num = (rand7()-1)*7+rand7() # 1-49
if num<=40:return 1+num%10 # 1-40
num = (num-40-1)*7+rand7() # 41-49 (0~9)*7
if num<=60:return 1+num%10 # 1-60
num = (num-60-1)*7+rand7() # 61-63 (0~3)*7
if num<=20:return 1+num%10 # 0-21