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" ; ?>