English 中文(简体)
数字序列转换为随机id吗?
原标题:
  • 时间:2009-04-15 00:48:04
  •  标签:

我工作在一个应用程序,我需要生成惟一的,不连续的id。的一个限制是,他们必须由3位紧随其后2字母(只有600 k id)。给我相对较小的IDs池正考虑简单地生成所有可能的id,拖着他们,让他们到一个数据库中。以后,在内部,我有一个简单的,连续的,使用ID,它会很容易拔出来一次&我一定不要有重复。

这感觉t并不像一个非常令人满意的解决方案。有人有一个更有趣的方法从有限生成惟一id比这彩票方法?

最佳回答

这可以做很多不同的方式,取决于你想优化(速度、内存使用情况等)。

ID = ddd模式c < a href = " http://en.wikipedia.org/wiki/Linear_feedback_shift_register " rel = " noreferrer " > 1 < / > c [0]

Option 1 (essentially like hashing, similar to Zak s):
1 Generate a random number between 0 and number of possibilities (676k).
2- Convert number to combination

    ddd = random / (26^2)
    c[0] = random % (26)
    c[1] = (random / 26) % 26

3 -查询数据库ID和增量的存在,直到找到一个免费。< br / > < br / >

Option 2 (Linear feedback shift register, see wikipedia):
1- Seed with a random number in range (0,676k). (See below why you can t seed with 0 )
2- Generate subsequent random numbers by applying the following to the current ID number

    num = (num >> 1) ^ (-(num & 1u) & 0x90000u);

3- Skip IDs larger than range (ie 0xA50A0+)
4- Convert number into ID format (as above)
*You will need to save the last number generated that was used for an ID, but you won t need to query the DB to see if it is used. This solution will enumerate all possible IDs except [000 AA] due to the way the LFSR works.

[编辑]因为你的范围实际上是大于你需要,你可以回到[000 AA]通过减去1转换为ID和之前有你的有效范围是(0,0 xa50a0]

问题回答

使用一个有限群。基本上,32或64位整数,和找到大量coprime整数的最大值;这个数M .然后,呼吁所有整数n, n * M将导致一个惟一的编号,有很多数字。

这样做的优势在于不需要预先填充数据库,或运行一个单独的select查询——你可以从内部一个insert语句,通过你的<代码> n > < /代码只是一个自动递增,和有一个单独的ID列,默认为n * M。

你可以生成一个随机的ID符合这个标准,做一个DB选择是否已经存在,然后将它插入一个DB要注意“使用”。第一生命的25%计划(约150 k条目),它应该是相对快速生成新的随机ID。虽然之后,它将越来越长,你不妨预先填充表寻找免费的ID。

Depending on what you define as sequential, you could just pick a certain starting point on the letters, such as aa , and just loop through the three digits, so it would be: 001aa 002aa 003aa

一旦zz然后增量部分数量。

你可以用模运算生成id。选择一个号码与676000和coprime种子。<代码> id > < /代码标准递增表的id。然后你需要下面的伪代码:

uidNo = (id * seed) % 676000
digits = uidNo / 676
char1 = uidNo % 26
char2 = (uidNo / 26) % 26
uidCode = str(digits) + chr(char1+65) + chr(char2+65)

如果用户有多个连续发行的id,可以猜测算法和种子和生成所有的id。这可能意味着你的用例的算法是不够安全。





相关问题
热门标签