Answer the question
In order to leave comments, you need to log in
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,
// ...
];
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question