当前位置:网站首页>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;
}
}
边栏推荐
- c#Sqlite类库
- 雷达发射机
- Building SQL statements in Excel
- Scroll, do you understand?
- 11. application layer data transmission format / port number -bite
- Lumiprobe reactive dye carboxylic acid: sulfo cyanine7.5 carboxylic acid
- Real software testers = "half product + Half development"?
- MySQL为什么选择B+树存储索引
- 14.ip protocol -bite
- Informatics Olympiad all in one 1002: output the second integer
猜你喜欢

Lumiprobe deoxyribonucleic acid phosphate CpG 1000 solid carrier

MCS: discrete random variable - binomial distribution

Implementing redis distributed locks using custom annotations

Differential equations of satellite motion

MCS: multivariate random variable - discrete random variable

分页sql(rownum、row_number、dense_rank、rank)

cmake学习-2

动作捕捉系统用于苹果采摘机器人

CKS CKA ckad change terminal to remote desktop

Chapter IX app project test (the end of this chapter)
随机推荐
Ink drop typesetting
Polarimetric SAR surface classification
Flink SQL任务TaskManager内存设置
Uncover the practice of Baidu intelligent test in the field of automatic test execution
Review of digital image processing
从雷达回波中可获取的信息
数字图像处理复习
Hi, you have a code review strategy to check
c#Sqlite类库
BFD原理与配置
中序和后序遍历构建二叉树[递归划分区间与回溯拼接子树+中后序和中前序的相似与不同]
极化SAR地表分类
MySQL开发规范.pdf
雷达天线简介
Rust Basics
BFD principle and configuration
Summary of recent work
11.应用层数据传输格式/端口号-bite
Paging SQL (rownum, row_number, deny_rank, rank)
Unity C # basic review 26 - first acquaintance Commission (p447)