How to write an elegant random Algorithm in php applications

Source: Internet
Author: User
My application: randomly generate an integer between-50 and 50 that does not include 0. I use mt_rand (-50, 50) and then judge whether the result is 0, if it is 0, it will be random again, but this is not elegant at all. Is there a better way? Further, if you want to control the ratio of generating positive and negative numbers... my application: randomly generate an integer between-50 and 50 that does not include 0. I use mt_rand (-50, 50) and then judge whether the result is 0, if it is 0, it will be random again, but this is not elegant at all. Is there a better way?

What else do you do if you want to control the ratio of the generated positive and negative numbers to 4: 6?

Reply content:

My application: randomly generate an integer between-50 and 50 that does not include 0. I use mt_rand (-50, 50) and then judge whether the result is 0, if it is 0, it will be random again, but this is not elegant at all. Is there a better way?

What else do you do if you want to control the ratio of the generated positive and negative numbers to 4: 6?

Function my_rand () {$ num = mt_rand (1, 50); $ rand = mt_rand (1, 10); return $ rand> 4? $ Num:-$ num ;}

1. randomly generate a batch of positive numbers
2. Make the first 60% of these numbers negative,
3. disrupt the order, and then retrieve it in order.

Thank you, echo array_rand (array (mt_rand (-50,-1), mt_rand )));

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.