Home  >  Article  >  Backend Development  >  PHP generates N non-repeating random number instances_PHP tutorial

PHP generates N non-repeating random number instances_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:14741browse

There are 25 works for voting. You need to select 16 works in one vote. A single work can only be selected once in one vote. A programmer made a mistake earlier and forgot to store the votes in the database. The voting sequences generated by 200 users were empty. So how do you fill this gap?
Of course, report the situation to your superiors. But what we are discussing here is technology, which requires generating 16 non-repeating random numbers between 1-25 to fill in. How to design the function specifically? Store random numbers in an array, and then remove duplicate values ​​in the array to generate a certain number of non-repeating random numbers.
The program is as follows:

Copy the code The code is as follows:

/*
* array unique_rand( int $min, int $max, int $num )
* Generate a certain number of non-repeating random numbers
* $min and $max: Specify the range of random numbers
* $num: Specify the number of generated
*/
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 = '';
for($i=0; $i < count($arr);$i++)
{
$result .= $arr[$i]. ',';
}
$result = substr($result, 0, -1);
echo $result;
?>


The program runs as follows :
Copy code The code is as follows:

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

A few additional notes:
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, key names may become discontinuous when deleting duplicate values, causing trouble in traversal.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825151.htmlTechArticleThere are 25 works for voting. You need to select 16 works in one vote. A single work can only be selected once in one vote. A programmer made a mistake earlier and forgot to store the votes in the database. 200 users generated...
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