已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
不要使用系统的 Math.random() 方法。
来源:力扣(LeetCode)
拒绝采样
a | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
b | ||||||||
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 1 | |
5 | 6 | 7 | 8 | 9 | 10 | 1 | 2 | |
6 | 7 | 8 | 9 | 10 | 1 | 2 | 3 | |
7 | 8 | 9 | 10 | 1 | 2 | 3 | 4 |
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
int
rand10()
{
int a = rand7 ();
int b = rand7 ();
int sum = a + b;
// 排除红色数字后,各数据出现概率等可能
if (a > 4&&b < 4)
{
return rand10 ();
}
else
{
return sum % 10 + 1;
}
}