dtjxhf595733 2016-01-31 22:28

# 随机数生成器过于重复某些数字

I'm writing a lottery draw simulation program as a project. The way the game works is you need to pick the 6 numbers that are draw from the 49 to win.

Your chance of winning is 1/13,983,816 because that's how many combinations of 6 in 49 there are. The <kbd>demo program on Go playground </kbd> generates six new numbers each time around the loop forever.

Each time a new set of numbers is generated I test to see if it already exists and if it does I break out of the loop. With 13,983,816 combinations you would think it would be a long time before the same 6 numbers would repeat but, in testing it fails always before 10000 iteration. Does anyone know why this is happening?

• 写回答

#### 3条回答默认 最新

• dougutuo9879 2016-01-31 23:11
关注

In my opinion you have a couple of problems here.

1. You use Go playground, where your randomness is fixed. This line `rand.Seed(time.Now().UnixNano())` always produce the same seed because `time.Now()` is the same.
2. You test completely different things with your simulation. I will write about it in the end.
3. if you want to do something similar to gambling - you have to use cryptographically secure PRNG and Go has it. If you want you can read more details here (the answer is to php question, but it explains the difference).

On the probability part:

The probability of winning your lottery is indeed `1/C(49, 6) = 1/13,983,816`. But this is the probability that someone would select an already predefined set of numbers. For example you claim that your winner is `{1, 5, 47, 3, 4, 5}` and now the probability that someone would win is approximately 1 in 14 mln. So you have to do the following. Randomly select a set of 6 numbers and then compare your new selection in a loop to already found.

But what you do is to check the probability of collision. That having N people some of them would select the same sets (not necessarily even the winning set). This is known as the birthday paradox. And as you see there, the probability of collision increase dramatically with the increase of number of people N.

This is absolutely the same problem, but your number of days in the year is `13,983,816` and you can check here that for this number of days you need only 5000 iterations to guarantee with 0.59 percents that you will get a collision. And with 9000 iterations you will find the collision with probability 0.94.

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 关于#网络#的问题：网络是从楼上引一根网线下来，接了2台傻瓜交换机，也更换了ip还是不行
• ¥15 资源泄露软件闪退怎么解决？
• ¥15 CCF-CSP 2023 第三题 解压缩(50％)
• ¥30 comfyui openpose报错
• ¥20 Wpf Datarid单元格闪烁效果的实现
• ¥15 图像分割、图像边缘提取
• ¥15 sqlserver执行存储过程报错
• ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
• ¥15 浮窗和全屏应用同时存在，全屏应用输入法无法弹出
• ¥100 matlab2009 32位一直初始化