Detailed explanation of generating N non-repeating random number instances in PHP_PHP Tutorial

WBOY
Release: 2016-07-13 10:43:44
Original
859 people have browsed it

I have told you about generating multiple random numbers before. Now I will introduce an example of generating N non-repeating random numbers in PHP. If you are interested, you can refer to it.

It is not difficult to implement this function, but it made me learn a lot.

* Generate a certain number of unique random numbers
The code is as follows
 代码如下 复制代码

/** 

 * 生成一定数量的不重复随机数 

 * @param int $min ,$max指定随机数的范围 

 * @param int $max 

 * @param int $num 指定生成数量 

 * @return array 

 */

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; 

}

Copy code



/**
* @param int $min, $max specifies the range of random numbers

* @param int $max

* @return array */ 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; } The mt_rand() function is used to generate random numbers. This function generates random numbers four times faster on average than rand(). The "flip method" is used to remove duplicate values ​​in the array, 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, key names may become discontinuous when deleting duplicate values, causing trouble in traversal. http://www.bkjia.com/PHPjc/633145.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633145.htmlTechArticleI have told you about generating multiple random numbers before. Now I will introduce another article about generating N random numbers in PHP. Examples of non-repeating random numbers. If you are interested, you can refer to it. To achieve this...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template