php generates N non repeating random number instances

  • 2020-11-20 06:02:13
  • OfStack

There are 25 pieces to be voted on, 16 pieces to be chosen for each vote, and only one piece to be chosen for each vote. A programmer made a mistake and forgot to put the votes in the database. There were 200 users who created an empty voting sequence. So how do you fill that hole?
Of course, report the situation to your superiors. But what we're talking about here is the technique of generating 16 non-repeating random Numbers between 1 and 25 to fill in. How do you design a function? Put the random number into the array, and then remove the repeated value in the array, to generate 1 fixed number of non-repeated random number.
The procedure is as follows:


<?php
/*
* array unique_rand( int $min, int $max, int $num )
*  generate 1 A fixed number of non-repeating random Numbers 
* $min  and  $max:  Specifies the range of random Numbers 
* $num:  Specified amount of generation 
*/
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:

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 on average four times faster than rand().
The "flip" method is used to remove duplicate values from the array. array_flip() is used to swap the array's key and value twice. This is much faster than using array_unique().
Before returning the array, use shuffle() to give the array a new key name, making sure the key name is a consecutive number from 0 to n. If you do not do this step, you may cause a key name discontinuity when deleting duplicate values, causing problems for traversal.


Related articles: