在PHP/MySQL中生成唯一代码? [英] Generating unique codes in PHP/MySQL?

查看:96
本文介绍了在PHP/MySQL中生成唯一代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与一个客户合作,该客户需要生成数百万个用于杂志刮刮卡,瓶盖奖品等的字母数字代码.它们必须足够短才能打印在大写字母上,它们要确保不包括诸如1和I,0和O等不明确的字符,并且必须明确地存储它们以备将来使用-我们可以只是有一种算法可以在有人尝试赎回时确定有效性".最后,他们希望确保这些代码随机分布在一个较大的代码空间"内,这样人们就不能只是通过遍历字母来猜测其他代码.

I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.

是否存在指向生成此类代码集的合理有效算法的指针?我在信封的背面划了一些痕迹,但是这个问题闻起来像个陷阱,给那些粗心的人.

Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.

推荐答案

例如,如果需要大约一千万个唯一键,则最好的方法是选择一个指数级更大的键空间,然后开始随机生成.阅读有关生日悖论的知识-这是您应该担心的主要事情.如果要使用2 ^ n个唯一且安全的密钥,请确保至少有2 ^(2 * n)个可能的值.这是一个粗略的O(n log n)算法:

If you need about 10 million unique keys (for example), the best approach is to pick a key-space that's exponentially bigger, and start randomly generating. Read about the Birthday Paradox -- it's the main thing you should be worried about. If you want 2^n unique and secure keys, make sure there are at least 2^(2 * n) possible values. Here's a rough O(n log n) algorithm:

  • 使用至少2 ^ 50的键空间(换句话说,允许2 ^ 50个可能的唯一值),并且整个数据集中几乎不会发生冲突-任何强行强制使用键的人都会如果他们尝试2 ^ 25,甚至有几率获得一把钥匙.
  • 根据需要生成任意数量的随机数
  • 在密钥上为数据库建立索引(这是O(n lg n)步骤:排序)
  • 遍历数据库并遍历整个数据集以修剪重复项(下面的伪代码)
  • 删除重复的行,您就完成了.

伪代码:

$last = null;
while ($current = getnext()) {
    if ($last == $current) {
        push($toDelete, $current);
    }
    $last = $current;
}

这篇关于在PHP/MySQL中生成唯一代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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