Home > Article > Backend Development > PHP generates 10 non-repeating random numbers
Question:
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?
It is necessary to generate 16 non-repeating random numbers between 1-25 to fill. 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:
<?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 = ''; for($i=0; $i < count($arr);$i++) { $result .= $arr[$i].','; } $result = substr($result, 0, -1); echo $result; ?>
The running results are as follows:
2,3,4,6,7,8,9,10,11,12,13,16,20,21,22,24
Additional instructions:
1. The mt_rand() function is used to generate random numbers. This function generates random numbers four times faster on average than rand().
2. When removing duplicate values from the array, the "flip method" is used, which is to use the array_flip() function to exchange the key and value of the array twice. This approach is much faster than using the array_unique() function.
3. Before returning the array, first use shuffle() to assign a new key name to the array, ensuring that the key name is a consecutive number from 0-n. If this step is not performed, the key names may be discontinuous when deleting duplicate values, causing trouble in traversal.
Recommended tutorial: PHP video tutorial
The above is the detailed content of PHP generates 10 non-repeating random numbers. For more information, please follow other related articles on the PHP Chinese website!