与6位随机字母数字代码发生冲突的可能性是多少? [英] What is the probability of collision with a 6 digit random alphanumeric code?

查看:87
本文介绍了与6位随机字母数字代码发生冲突的可能性是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下perl代码生成随机的字母数字字符串(仅大写字母和数字),用作我的MySQL数据库中记录的唯一标识符.该数据库可能会保留在1,000,000行以下,但实际的绝对最大值约为3,000,000.我会有2条记录具有相同随机代码的危险机会吗,还是发生的次数很少?我对概率知之甚少(如果从这个问题的性质上还不能很清楚地知道这一点),并且会喜欢某人的意见.

I'm using the following perl code to generate random alphanumeric strings (uppercase letters and numbers, only) to use as unique identifiers for records in my MySQL database. The database is likely to stay under 1,000,000 rows, but the absolute realistic maximum would be around 3,000,000. Do I have a dangerous chance of 2 records having the same random code, or is it likely to happen an insignificantly small number of times? I know very little about probability (if that isn't already abundantly clear from the nature of this question) and would love someone's input.

perl -le 'print map { ("A".."Z", 0..9)[rand 36] } 1..6'

推荐答案

由于生日悖论可能性超出您的想象.

Because of the Birthday Paradox it's more likely than you might think.

有2,176,782,336个可能的代码,但是即使仅插入50,000行,也已经有很高的发生碰撞的机会.对于1,000,000行,几乎不可避免地会发生许多冲突(我认为平均有250次冲突).

There are 2,176,782,336 possible codes, but even inserting just 50,000 rows there is already a quite high chance of a collision. For 1,000,000 rows it is almost inevitable that there will be many collisions (I think about 250 on average).

我进行了一些测试,这是在第一次碰撞发生之前我可以生成的代码数:

I ran a few tests and this is the number of codes I could generate before the first collision occurred:

  • 73366
  • 59307
  • 79297
  • 36909

随着代码数量的增加,冲突将变得更加频繁.

Collisions will become more frequent as the number of codes increases.

这是我的测试代码(用Python编写):

Here was my test code (written in Python):

>>> import random
>>> codes = set()
>>> while 1:
        code=''.join(random.choice('1234567890qwertyuiopasdfghjklzxcvbnm')for x in range(6))
        if code in codes: break
        codes.add(code)

>>> len(codes)
36909

这篇关于与6位随机字母数字代码发生冲突的可能性是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆