PHP test-specify a probability Random Number

Source: Internet
Author: User

A large company has the following PHP test questions:

 
Please write oneProgram, Randomly print "0", "1", "2", but ensure that "0", "1", "2" appear probability is configurable, such.

At first glance, the solution comes into being --

<? PHP  $ = $ B = $ C = 0 ;  $ Array = Array (0, 0, 1, 2, 2 );  For ( $ I = 1; $ I <1, 6001;$ I ++ ){  $ T = Array_rand ( $ Array  );  If ( $ T = 0 ){  $ ++ ;}  If ( $ T = 1 ){  $ B ++ ;}  If ( $ T = 2 ){  $ C ++ ;}}  Echo   $  ;  Echo "\ N" ;  Echo   $ B  ;  Echo "\ N";  Echo   $ C  ;  Echo "\ N" ; ?>

What is the result ~~~~

The probability is not controlled ~~~

Finally, I found a good method on the Internet. In fact, it's really easy to think about it. I just didn't turn it over. Hahaha ~~~

<? PHP  $ = $ B = $ C = 0 ;  For ( $ I = 1; $ I <1, 6001; $ I ++ ){  $ Temp = Rand (0, 60 );  If ( $ Temp <20 ){  $ ++ ;}  Elseif (20 <= $ Temp && $ Temp <30 ){  $ B ++ ;}  Else  {  $ C ++ ;}}  Echo   $  ;  Echo "\ N" ;  Echo   $ B  ;  Echo "\ N" ;  Echo   $ C  ;  Echo "\ N" ; ?>

Good results ~~

 

Rewrite to function:

<? PHP  Function Getrandom ( $ Array , $ Rate  ){  $ Rate = Explode (':',$ Rate  );  $ Sum = 0 ;  $ Left = 0 ;  $ Right = 0 ;  Foreach ( $ Rate   As   $ Value  ){  $ Sum + = $ Value * 10;}  $ Temp = Rand (0, $ Sum  );          Foreach ( $ Rate   As   $ Key => $ Value  ){  $ Right + = $ Value * 10 ;  If ($ Left <= $ Temp && $ Temp < $ Right  ){  Return   $ Array [ $ Key  ];}  $ Left + = $ Value * 10 ;}}  $ Array = Array (0, 1, 2, 3);  $ Rate = '2: 1: 3: 5' ;  $ = $ B = $ C = $ D = 0 ;  For ( $ I = 0; $ I <1, 1100; $ I ++ ){  If (Getrandom ($ Array , $ Rate ) = 0 ){  $ ++ ;}  If (Getrandom ( $ Array , $ Rate ) = 1 ){  $ B ++ ;}  If (Getrandom ( $ Array , $ Rate ) = 2 ){  $ C ++ ;}  If (Getrandom ( $ Array , $ Rate ) = 3 ){  $ D ++ ;}}  Echo   $  ;  Echo "\ N" ; Echo   $ B  ;  Echo "\ N" ;  Echo   $ C  ;  Echo "\ N" ;  Echo   $ D  ;  Echo "\ N" ; ?>

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.