php2000在1000和9999之间的唯一随机数


php 2000 unique random numbers between 1000 and 9999

我想生成2000个范围在1000到9999之间的唯一随机数。我正在做这样的事情,但它不是生成唯一的数字。

$numbers = array();             
// Loop while there aren't enough numbers
while (count($numbers) < 2000) {
    $random_number = rand(1000, 9999);
    if (!in_array($random_number, $numbers)) {             
       // This adds the number to the array      
       $numbers[] = 'A'.$random_number.'14';
    }
}

请帮忙。

对于这样的小范围,我宁愿使用这种方法:

$candidates = range(1000, 9999);
shuffle($candidates);
$numbers = array_slice($candidates, 0, 2000);
$numbers = array_map(function ($number) { return "A{$number}14"; }, $numbers);

您检查是否存在一个数字,比如4567,但添加了'A456714',所以找不到该数字。

你可以这样修复:

$numbers = array();             
// Loop while there aren't enough numbers
while (count($numbers) < 2000) {
    $random_number = rand(1000, 9999);
    $code = 'A'.$random_number.'14';
    if (!in_array($code, $numbers)) {             
       // This adds the number to the array      
       $numbers[] = $code;
    }
}

我必须说,欺骗的解决方案也很好(实际上更好(。不同的是,在他的解决方案中,你根本不会有任何双数需要检查,所以大多数时候可能会更快。

缺点是你会有一个相对较大的数组,有9000个数字。对于这种特定的情况,他的解决方案可能会更好,但如果你选择较小数量的随机数,或者从较大的范围中选择,这个(你自己的(解决方案可能更好。如果你想从range(100, 1000000)中选择100个随机数,那么这个解决方案可能会更好,因为选择一个双数的机会非常小,而且检查它非常轻。

很难说临界点在哪里,但就你目前的情况而言,我会选择他的。

与其检查数组中是否已经存在数字,不如尝试以下操作:

<?php
$numbers=array();
while (count($numbers)<2000)
{
    $numbers['A'.rand(1000,9999).'14']=true;
}
$unique=array_keys($numbers);
echo print_r($unique,true).PHP_EOL;

它使用数组键是唯一的这一事实来消除数组检查。我想计算数组中元素的数量要快得多

这是因为您将A和14添加到要放入数组$numbers的每个数字中。。所以,对于你生成的每个数字,下一个循环中都不会有任何相同的数字。。

抱歉我英语不好。。

random.org API:

$numbers = explode(PHP_EOL,
    file_get_contents(
        'http://www.random.org/integers/?num=2000&min=1000&max=9999&col=1&base=10&format=plain&rnd=new'
    )
);

$numbers = array_map(function($v) {
    return 'A' . $v . '14';
}, $numbers);
function random_in_rang($min, $max, $count)
{
    $numbers = array();
    for($i=0; $i<$count; $i++)
    {
        //decrease range after adding a new random value
        $rnd = rand($min, $max-$count);
        //new value should be unique
        while(isset($numbers[$rnd])) $rnd++;
    }
    return array_keys($numbers);
}

一种更有效的大范围方式(速度和内存使用(:

function get_unique_random_numbers($min,$max,$count) {
    $numbers = array();
    while( count($numbers) < $count ) {
          $numbers["A".mt_rand($min,$max)."14"] = 1;
    }
    return array_keys($numbers);
}
$numbers = get_unique_random_numbers(0,90000000,20000);
// < 0.X seconds

当CCD_ 4。但当($max-$min) ~ $count。当($max-$min) < $count

所以要小心。:(最后在开始循环之前进行检查。