公式:(randX() - 1)*Y + randY() 可以等概率的生成[1, X * Y]范围的随机数
/**
* 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() {
while(true){
int a = rand7(), b = rand7();
//num = rand49()
int num = (a - 1) * 7 + b;
//当num>40时拒绝采样
if(num <= 40) return num % 10 + 1;
/*接下来利用抛弃掉的尾数继续产生随机数以减少循环次数*/
//a = rand9(), num = rand63()
a = num - 40; b = rand7();
num = (a - 1) * 7 + b;
if(num <= 60) return num % 10 + 1;
//a = rand3(), num = rand21()
a = num - 60; b = rand7();
num = (a - 1) * 7 + 7;
if(num <= 20) return num % 10 + 1;
}
}
}