L
L
l4m3r2018-11-07 17:01:42
PHP
l4m3r, 2018-11-07 17:01:42

How to make a random from an array with a specified probability for elements?

There is an array like:

$a = [
     'a' => 1,
     'b' => 0.11,
     'c' => 0.5,
     'd' => 1,
     'e' => 0.02,
     'f' => 0.0000005,
// ...
];

Values ​​in the array != probability (0 - 1), but only weight / frequency.
I need to make such a random, which most often will return the key that has more weight.
Those. according to the example above, 'a' or 'd' will most often fall out, extremely rarely 'e'
PS: there was a similar topic, but it's a bit different there.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-11-07
@l4m3r

Add up all the weights. Their sum is 100%, "one".
Take a random number from 0 to 1.
Project it onto your range, see where you hit.

$sum = array_sum($a);
$rnd = rand() / getrandmax(); // от 0 до 1
$runningSum = 0;
foreach($a as $k => $v) {
  $runningSum += $v / $sum;
  if ($runningSum >= $rnd) {
    $key = $k;
    break;
  }
}
if (!$key) $key = $k;

echo "Выпало: " . $key . PHP_EOL;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question