Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a random value from array with probability proportional to it's value

I have an array like

$keywords = array('apple'=>10,'orange'=>2,'grape'=>12); 

I want to randomly pick one of the "Key" from the array. However the probability distribution should be such that probability of picking an element should be proportional to it's value.

like image 463
Eastern Monk Avatar asked Nov 26 '11 18:11

Eastern Monk


2 Answers

Add all values (10+2+12 is 24); get a random number in the range [0, 24), and pick the corresponding element depending on whether the number lies in [0, 10), [10, 12), or [12, 24).

like image 114
Kerrek SB Avatar answered Sep 30 '22 00:09

Kerrek SB


I'd do it like this:

    $probabilities = array('apple'=>50, 'orange'=>20, 'banana'=>10);

    function random_probability($probabilities) {
      $rand = rand(0, array_sum($probabilities));
      do {
        $sum = array_sum($probabilities);
        if($rand <= $sum && $rand >= $sum - end($probabilities)) {
          return key($probabilities);
        }
      } while(array_pop($probabilities));
    }
like image 25
Peter Briers Avatar answered Sep 30 '22 01:09

Peter Briers