当前位置:网站首页>LeetCode-470-用Rand7()实现Rand10()
LeetCode-470-用Rand7()实现Rand10()
2022-06-29 15:26:00 【z754916067】
题目

思路
- 之前做过这种题,虽然已经完全忘记了,还是想不太出来,去看题解了。
- 例如使用rand2求rand4,如果使用(rand2()-1+rand2()),可以计算出其范围在[1,3]之间,虽生成的值确实在[1,4]之间,但不符合条件。
- 但如果是2*(rand2()-1)+rand2(),可以计算出其在[1,4]之间。
- 故很明显,就是要找出把[1,7]化成[1,10]的算式,根据以上经验,总之要先化出[0,x]出来,考虑将rand7()-1,成为[0,6]的值,为让其范围在7的倍数中,将其x7,成为[0,42],为了让左边界为7,再加上rand7(),成为[1,49]
- 此时,可以使用rand7()得到rand49(),且各个概率皆均匀,即12345678910这十个数字是均匀的,虽然相加不为1。
- 那么后续很明显,抛弃所有不为[1,10]或者将获得的所有化成[1,10]即可。
代码
public int rand10() {
while(true){
//用rand7()实现rand10()
int num=0;
num=(rand7() - 1) * 7 + rand7(); //等概率生成[1,49]
if(num>=40) return num%10+1;
}
}
边栏推荐
- 动作捕捉系统用于苹果采摘机器人
- 服务器的数据库连不上了【服务已起、防火墙已关、端口已开、netlent 端口不通】
- 14.ip protocol -bite
- Neural network for remote sensing image processing
- I am 35 years old. Can I change my career to be a programmer?
- TDesign, which gave us benefits last time, will tell us its open source story today
- Scroll, do you understand?
- 复数卷积神经网络:CV-CNN
- MCS: discrete random variable Poisson distribution
- Chaîne lumineuse libre biovendor κ Et λ) Propriétés chimiques du kit ELISA
猜你喜欢

File common tool class, stream related application (record)

14.ip protocol -bite

深度学习遥感数据集

MCS: discrete random variable - binomial distribution

Unity C # basic review 26 - first acquaintance Commission (p447)

MCS: discrete random variables - geometric distribution

Solution to the problem that the assembly drawing cannot be recognized after the storage position of SolidWorks part drawing is changed

Paging SQL (rownum, row_number, deny_rank, rank)

Uncover the practice of Baidu intelligent test in the field of automatic test execution

Lumiprobe deoxyribonucleic acid phosphate CpG 1000 solid carrier
随机推荐
Middle order and post order traversal to construct binary tree [recursive partition interval and backtracking splicing subtree + similarity and difference between middle post order and middle pre orde
For example, the visual appeal of the live broadcast of NBA Finals can be seen like this?
Pytorch two-dimensional multi-channel convolution operation method
Introduction to radar related contents
kotlin 注解声明与使用
89.(cesium篇)cesium聚合图(自定义图片)
Mysql database naming conventions PDF
Northwestern Polytechnic University attacked by overseas e-mail
Symfony framework security component firewall configuration
Informatics Olympiad all in one 2061: trapezoidal area
List集合详细讲解
Rust Basics
13.TCP-bite
雷达天线简介
Rust基础知识
Get the width of text component content
复数卷积神经网络:CV-CNN
c#Sqlite类库
LeetCode笔记:Biweekly Contest 81
Hi, you have a code review strategy to check