Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to select maximum probability value randomly?

I have below array & code

    $a = [
      149 => 55,
      130 => 10,
      131 => 5,
      132 => 5,
      133 => 10,
      134 => 10,
      135 => 5
    ];

   $rand = rand (0,(count($a)-1));

   echo array_values($a)[$rand];

This will give majorly result as 5,10 instead of 55.

Total of value is 100% probability. Values can be in decimal as well like 55.55, 10.10, etc. but overall going to be 100%

I already followed https://www.geeksforgeeks.org/how-to-get-random-value-out-of-an-array-in-php/

But this is not giving perfect result as expected.

So which has highest probability should be selected majorly and randomly.

So result can be like this : 55, 55, 10, 10, 10, 55, 5, etc..

I found some useful link Generating random results by weight in PHP? where Probability = Weight

like image 519
Jackson Avatar asked Dec 23 '22 18:12

Jackson


1 Answers

Right now, your array is this: -

55, 10, 5, 5, 10, 10, 5

Now, you should generate a random number between [0, 100), let's call it r.

  • Now, if r lies between [0, 55), select the value 55.
  • else if r lies between [55, 55 + 10 = 65), select the value 10.
  • else if r lies between [65, 65 + 5 = 70), select the value 5.
  • else if r lies between [70, 70 + 5 = 75), select the value 5.
  • else if r lies between [75, 75 + 10 = 85), select the value 10.
  • else if r lies between [85, 85 + 10 = 95), select the value 10.
  • else if r lies between [95, 95 + 5 = 100), select the value 5.

I am sure you would have got the idea...

So, for the general case, if you have an array named 'arr', this is the pseudocode: -

function SELECTPROB()
{
    $r = generateRandomNumber(0, 100);    //function to generate random number between 0 and 100, (100 exclusive)
    $sum = 0;
    foreach($arr as $i)
    {
        if($r >= $sum && $r < $sum + $i)
        {
            return $i
        }
        $sum = $sum + $i
    }
    return -1    //Should technically never reach upto this, but it can if your probability's sum is not 100
}
like image 82
EReload Avatar answered Jan 19 '23 03:01

EReload