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 procedure is as follows:
$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:
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.