当前位置:网站首页>Leetcode-470- implement rand10() with rand7()
Leetcode-470- implement rand10() with rand7()
2022-06-29 15:48:00 【z754916067】
subject

Ideas
- I have done this problem before , Although I have completely forgotten , I still can't figure it out , Go and see the solution .
- For example, using rand2 seek rand4, If you use (rand2()-1+rand2()), It can be calculated that the range is [1,3] Between , Although the generated values are indeed [1,4] Between , But it doesn't meet the conditions .
- But if it is 2*(rand2()-1)+rand2(), It can be calculated that [1,4] Between .
- So obviously , Is to find out [1,7] turn [1,10] The formula of , Based on the above experience , In short, we must first turn out [0,x] come out , consider rand7()-1, Become [0,6] Value , In order to make its scope in 7 In multiple of , Put it x7, Become [0,42], To make the left boundary 7, Plus rand7(), Become [1,49]
- here , have access to rand7() obtain rand49(), And each probability is uniform , namely 12345678910 These ten figures are uniform , Although the sum is not 1.
- Then the follow-up is obvious , Abandon all not for [1,10] Or turn all you get into [1,10] that will do .
Code
public int rand10() {
while(true){
// use rand7() Realization rand10()
int num=0;
num=(rand7() - 1) * 7 + rand7(); // Equal probability generation [1,49]
if(num>=40) return num%10+1;
}
}
边栏推荐
猜你喜欢
随机推荐
Introduction to radar antenna
Rust Basics
C SQLite class library
CSDN无法复制问题
MySQL定时整库备份&滚动删除指定日期前的备份数据
如何使用SMS向客户传递服务信息?指南在这里!
89.(cesium篇)cesium聚合图(自定义图片)
. Net program configuration file operation (INI, CFG, config)
卷积神经网络中各层的作用
CKS CKA ckad change terminal to remote desktop
架构实战营模块五作业
Excel中构建SQL语句
kotlin 注解聲明與使用
《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
智能聊天机器人的优势在哪里?资深独立站卖家告诉你!
radar transmitter
Cmake learning-2
.NET程序配置文件操作(ini,cfg,config)
Taro中添加小程序 “lazyCodeLoading“: “requiredComponents“,
动态监听DOM元素高度变化









