I have previously told you how to generate multiple random numbers. Next I will introduce how to generate N non-repeated random number instances in php. If you are interested, refer to it.
It is not difficult to implement this function, but I have learned a lot.
The Code is as follows: |
Copy code |
/** * Generate a certain number of non-repeated random numbers * @ Param int $ min, $ max specifies the range of random numbers * @ Param int $ max * @ Param int $ num indicates the number of instances to be generated. * @ Return array */ 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; } |
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.