生成唯一的随机数聪明的方法 [英] smart way to generate unique random number

查看:127
本文介绍了生成唯一的随机数聪明的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要生成在00000001范围内独一无二的随机数到99999999序列。

i want to generate a sequence of unique random numbers in the range of 00000001 to 99999999.

所以,第一个可能是00001010,第二40002928等。

So the first one might be 00001010, the second 40002928 etc.

最简单的办法是产生一个随机数,并将其存储在数据库中,每下一次再做一次,并在数据库中检查该号已经存在,如果是这样,生成一个新的,检查一遍,等
但是,这看起来不正确,我可以再生一个数字,也许100次,如果产生的项目数量变大。

The easy way is to generate a random number and store it in the database, and every next time do it again and check in the database if the number already exists and if so, generate a new one, check it again, etc. But that doesn't look right, i could be regenerating a number maybe 100 times if the number of generated items gets large.

有没有更聪明的方式?

编辑
作为传真我忘了说为什么我想这一点,它可能会使事情更清晰,可能得到另一种选择,它是:
我们要生成一个预约的订单编号,所以我们可以只使用000001,000002等,但我们不希望给竞争对手多少线索订单创建(因为它不是一个高容量的市场,我们不想让他们知道,如果我们是在为了30 2个月后,或在订单100所以我们希望有一个订单号码是随机的(但唯一)

EDIT as allways i forgot to say WHY i wanted this, and it will probably make things clearer and maybe get an alternative, and it is: we want to generate an ordernumber for a booking, so we could just use 000001, 000002 etc. But we don't want to give the competitors a clue of how much orders are created (because it's not a high volume market, and we don't want them to know if we are on order 30 after 2 months or at order 100. So we want to have an order number which is random (yet unique)

推荐答案

您可以建立在它的所有可能的数字表,给记录的拿来主义领域。

You could build a table with all the possible numbers in it, give the record a 'used' field.


  1. 选择还没有被拿来主义的所有记录

  2. 选择一个随机数(R) 1和记录计数

  3. 以记录数r

  4. 从记录

  5. 获得你的随机值<李之>设置'使用'标志,并更新数据库。
  1. Select all records that have not been 'used'
  2. Pick a random number (r) between 1 and record count
  3. Take record number r
  4. Get your 'random value' from the record
  5. Set the 'used' flag and update the db.

这应该是比挑选的随机数,查询数据库更加高效,重复,直到没有发现因为这只是乞讨的一个永恒过去几年的值。

That should be more efficient than picking random numbers, querying the database and repeat until not found as that's just begging for an eternity for the last few values.

这篇关于生成唯一的随机数聪明的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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