Php generates N random number instances that are not repeated. You can vote for 25 pieces of data. you can only vote for 16 pieces of data at a time. In front of a programmer, he forgot to put the voting into the database. 200 users generated 25 pieces of work to vote. in one vote, he needed to select 16 pieces, A single file can only be selected once for one vote. The previous programmer threw a loophole and forgot to put the voting into the database. the voting sequence generated by 200 users was empty. So how do you fill in this leak?
Of course, reflect the situation to the superior. However, we will discuss the technology here, that is, we need to generate 16 non-repeated random numbers between 1 and 25 to fill. How to design functions? Store a random number into an array, and then remove duplicate values in the array to generate a certain number of non-repeated random numbers.
The procedure is as follows:
The code is as follows:
/*
* Array unique_rand (int $ min, int $ max, int $ num)
* Generate a certain number of non-repeated random numbers
* $ Min and $ max: specify the random number range.
* $ Num: specifies the number of instances generated.
*/
Function unique_rand ($ min, $ max, $ num ){
$ Count = 0;
$ Return = array ();
While ($ count <$ num ){
$ Return [] = mt_rand ($ min, $ max );
$ Return = 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:
The code is as follows:
Additional notes:
The mt_rand () function is used to generate a random number. The average speed of this function to generate random numbers is four times faster than rand.
When the repeated values in the array are removed, the "flip method" is used to exchange the key and value of the array twice with array_flip. This approach is much faster than using array_unique.
Before returning an array, use shuffle () to assign a new key name to the array to ensure that the key name is a continuous number ranging from 0 to n. If you do not perform this step, the key name may not be consecutive when you delete duplicate values, which may cause trouble for traversal.
Bytes. There was a programmer who had missed out and forgot to put the voting into the database. there were 200 users to generate...