4

i have the following array:

public $percentage = array(
   0 => 20.30,
   1=> 19.96,
   2=> 14.15,
   3=> 45.59
);

// it sums in 100%

I need a random function to return the key by the percentage of the value,

for example: the possibility to get 0 is 20.30% and the possibility to get 2 is 14.15%, the first user got 0, the second one got 2.

Please let me know what is the function you suggest me to use.

3
  • 1
    what exactly the function must do? I can't imagine Commented Mar 24, 2013 at 10:09
  • 1
    you want a function which has probability of 20.3% to return 0, 14.15% to return 2 etc? Commented Mar 24, 2013 at 10:16
  • Do you extractly 20.30% probability for zero Commented Mar 24, 2013 at 10:23

4 Answers 4

7

Convert the percentages to an accumulated probability, then compare it with a random number.

If the random number falls into a category, outputs the result. If not, move onto the next one until one is found. This allows you to output a number based on the percentage probability stated in the array.

$percentage = array(
   0 => 20.30,
   1=> 19.96,
   2=> 14.15,
   3=> 45.59
);
$random = mt_rand(0,10000)/100;
foreach ($percentage as $key => $value) {
    $accumulate += $value;
    if ($random <= $accumulate) {
        echo $key;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2
$random_n = mt_rand(0,10000)/100;
while(true){
  if($random_n <= $percentage[0])
    echo 0; break;
  else if($random_n <= $percentage[1])
    echo 1; break;
  else if($random_n <= $percentage[2])
    echo 2; break;
  else if($random_n <= $percentage[3])
    echo 3; break;
  else
    $random_n = mt_rand(0,10000)/100; //generate a new random #
}

1 Comment

No. The problem is, you have a random number generated, let's say it is 10, then according to the array, 0 is given as the result. If the random number is 25, 3 is given as the result. And if the random number is 50, nothing will be shown.
1
<?php
$percentage = $tmp = array(
   0 => 20.30,
   1=> 19.96,
   2=> 14.15,
   3=> 45.59
);

sort($tmp);

$rand = mt_rand(0,100);
foreach($tmp as $percent) {
    if($percent >= $rand) {
        echo array_search($percent,$percentage);
        die();
    }
}

echo (count($percentage) - 1);

Comments

0

I'd do something like:

  1. Take a random number between 1 and 10000 (because you have four significant digits)
  2. If the number is between 1 and 2030 then it's a zero, if it's between 2031 and (2031+1996) then it's a 1 etc.
  3. ...
  4. Profit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.