5位mt_rand()数的唯一性如何?

Bim*_*del 4 php

我只是想知道,如果你绘制5位数字,mt_rand()数是多么独特?在这个例子中,我试图用这个函数得到500个随机数的列表,其中一些是重复的.

http://www.php.net/manual/en/function.mt-rand.php

<?php
header('Content-Type: text/plain');

$errors = array();
$uniques = array();
for($i = 0; $i < 500; ++$i)
{
    $random_code = mt_rand(10000, 99999);
    if(!in_array($random_code, $uniques))
    {
        $uniques[] = $random_code;
    }
    else
    {
        $errors[] = $random_code;
    }
}

/**
 * If you get any data in this array, it is not exactly unique
 * Run this script for few times and you may see some repeats
 */
print_r($errors);
?>
Run Code Online (Sandbox Code Playgroud)

可能需要多少位数才能确保循环中绘制的前500个随机数是唯一的?

Jos*_*bou 7

如果数字是真正随机的,那么数字将被重复的概率.无论有多少位数都没关系 - 添加更多数字会使得重复的可能性降低,但总是有可能.

你最好检查一下是否存在冲突,然后循环直到不是这样:

$uniques = array();
for($i = 0; $i < 500; $i++) {
    do {
        $code = mt_rand(10000, 99999);
    } while(in_array($code, $uniques));
    $uniques[] = $code
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*hen 5

为什么不使用范围,随机播放和切片?

<?php

$uniques = range(10000, 99999);
shuffle($uniques);
$uniques = array_slice($uniques, 0, 500);

print_r($uniques);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => 91652
    [1] => 87559
    [2] => 68494
    [3] => 70561
    [4] => 16514
    [5] => 71605
    [6] => 96725
    [7] => 15908
    [8] => 14923
    [9] => 10752
    [10] => 13816
    *** truncated ***
)
Run Code Online (Sandbox Code Playgroud)

此方法较便宜,因为每次都不搜索数组以查看是否已添加项目.也就是说,它确实使这种方法不那么"随机".应提供有关这些数字将在何处使用的更多信息.如果这是一个在线赌博网站,这将是最糟糕的!但是,如果这用于为星座网站返回"幸运"号码,我认为这样会好的.

此外,可以扩展此方法,将shuffle方法更改为使用mt_rand(其中原始方法仅使用rand).它也可能使用openssl_random_pseudo_bytes,但这可能有点过分.