Home  >  Article  >  Backend Development  >  PHP generates N non-repeating random number example code

PHP generates N non-repeating random number example code

怪我咯
怪我咯Original
2017-07-11 11:37:491142browse

This article mainly describes how to use php to generate N non-repeating random number instances. The code is as follows:

<?php
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/
function unique_rand($min, $max, $num) {
    $count = 0;
    $return = array();
    while ($count < $num) {
        $return[] = mt_rand($min, $max);
        $return = array_flip(array_flip($return));
        $count = count($return);
    }
    shuffle($return);
    return $return;
}
$arr = unique_rand(1, 25, 16);
sort($arr);
$result = &#39;&#39;;
for($i=0; $i < count($arr);$i++)
{
 $result .= $arr[$i].&#39;,&#39;;
}
$result = substr($result, 0, -1);
echo $result;
?>

The program runs as follows:

The code is as follows:

2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24

Additional remarks:
The mt_rand() function is used to generate random numbers. This function generates random numbers four times faster on average than rand().
When removing duplicate values ​​from the array, the "flip method" is used, which is to use array_flip() to exchange the key and value of the array twice. This approach is much faster than using array_unique().
Before returning the array, first use shuffle() to assign new key names to the array, ensuring that the key names are consecutive numbers from 0-n. If this step is not performed, the key names may be discontinuous when deleting duplicate values, causing trouble in traversal.

The above is the detailed content of PHP generates N non-repeating random number example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn