生成长度为7个字符的唯一随机字母数字字符 [英] Generate unique random alphanumeric characters that are 7 characters long

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

问题描述

它不必是有意义的词-更像是随机密码生成,但要注意的是-它们应该是唯一的.我将把它用于某种包装/产品代码.哪一种是最好的方法? :)

It need not be meaningful words - more like random password generation, but the catch is - they should be unique. I will be using this for some kind of package / product code. Which is the best method available? :)

推荐答案

通常无法生成同时包含唯一元素和随机元素的序列:显然,唯一的是,算法必须考虑序列中先前生成的元素,因此下一个并不是真正随机的.

It is generally not possible to generate sequences with both unique and random elements: obviously to be unique the algorithm has to take into account the previously generated elements in the sequence, so the next ones will not really be random.

因此,最好的选择是检测冲突并重试(在您的特定情况下这可能会非常昂贵).

Therefore your best bet would be to detect collisions and just retry (which could be very expensive in your particular case).

如果您只限于7个字符,则上面没有什么可以做的:

If you are constrained to just 7 chars, there's not much you can do above:

$allowed_chars = 'abcdefghijklmnopqrstuvwxz';
$allowed_count = strlen($allowed_chars);
$password = null;
$password_length = 7;

while($password === null || already_exists($password)) {
    $password = '';
    for($i = 0; $i < $password_length; ++$i) {
        $password .= $allowed_chars{mt_rand(0, $allowed_count - 1)};
    }
}

这最终应该为您提供一个新密码.

This should eventually give you a new password.

但是,在类似的情况下,我通常会选择一个较大的密码,该密码也恰好是流行的哈希函数(例如md5)的十六进制表示的大小.然后,您可以使自己更轻松,并且不易出错:

However, in similar cases I have encountered I usually pick a larger password size which also happens to be the size of the hex representation of a popular hash function (e.g. md5). Then you can make it easier on yourself and less error prone:

$password = time(); // even better if you have some other "random" input to use here

do {
    $password = md5(time().$password);
}
while (already_exists($password));

这还具有额外的优点,即序列空间较大,因此冲突较少.您可以根据将来将要生成的密码的预期数量来选择哈希函数的大小,以保证"较低的冲突概率,从而减少对可能昂贵的already_exists函数的调用.

This also has the added advantage that the sequence space is larger, hence there will be less collisions. You can pick the size of the hash function according to the expected numbers of passwords you will generate in the future to "guarantee" a low collision probability and thus less calls to the possibly expensive already_exists function.

这篇关于生成长度为7个字符的唯一随机字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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