假设我们有一个函数rand7生成一个1到7范围内的统一随机整数,我们必须编写另一个函数rand10生成一个1到10范围内的统一随机整数。我们不能使用某些库函数来生成随机数。
假设我们想要两个随机数,那么它们可能是[8,10]。
为了解决这个问题,我们将遵循以下步骤-
rand40:= 40
而rand40> = 40
rand40:=(rand7()-1)* 7 +(rand7()– 1)
返回rand40 mod 10 +1
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
int rand7(){
return 1 + rand() % 7;
}
class Solution {
public:
int rand10() {
int rand40 = 40;
while(rand40 >= 40){
rand40 = (rand7() - 1) * 7 + (rand7() - 1);
}
return rand40 % 10 + 1;
}
};
main(){
srand(time(NULL));
Solution ob;
cout << (ob.rand10()) << endl;
cout << (ob.rand10()) << endl;
cout << (ob.rand10()) << endl;
}Call the function three times
输出结果
2 2 6