Php generates N non-repeated random number instances

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.