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.
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).
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With