题目描述
给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。
你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。
每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。
样例描述
示例 1:
输入: 1
输出: [2]
示例 2:
输入: 2
输出: [2,8]
示例 3:
输入: 3
输出: [3,8,10]
思路
递归 + k进制 + 随机概率平均 + 拒绝采样
按照10的倍数分成四组,注意分的时候先减一,方便写代码
代码
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
class Solution extends SolBase {
public int rand10() {
int t = (rand7() - 1) * 7 + rand7(); // 1~49的数
//如果大于40就递归调用原函数 直到t在1~40
if (t > 40) return rand10();
//四个一组分成10组,保证随机到每个组的概率相等, 让下标从0开始方便分组,记得补回1
return (t - 1) % 10 + 1;
}
}