Interview questions PHP random get probability results

Source: Internet
Author: User

Title: Random Output "apple", "orange", "banana" demand output "apple" probability is 50%, "orange" probability is 30%, "banana" probability is 20%

Analysis

Programme one:

The most commonly used rand (1,10) to handle output from apples 6 to 8 oranges 9 to 10 bananas if it is 5 or less output

<?PHP$arr=Array(' Apples ', ' oranges ', ' bananas ');$i=Mt_rand(1,10);if($i<=5){Echo $arr[0];}Else if($i>=9){Echo $arr[1];}Else{Echo $arr[2];}

It's not scientific, however, because Rand is so unreliable.

Scenario Two:

Array_rand to handle it.

<? PHP $arr Array (' Apples ', ' apples ', ' apples ', ' apples ', ' apples ', ' oranges ', ' oranges ', ' oranges ', ' bananas ', ' bananas '); $key=array_rand($arr); $arr [$key];? >

Is this really true? Not flattering.

Programme III:

Str_shuffle to handle it.

<? PHP $array=array(' 1 ' = ' apple ', ' 2 ' = ' orange ', ' 3 ' = ' banana '); $string= "1111122233"; $key=str_shuffle($string); Echo $array [$key{0}];? >

Looks like I think it's the most reliable.

Interview questions PHP random get probability results

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.