Answer the question
In order to leave comments, you need to log in
How to select array element based on rating?
Ladies and gentlemen, help solve one problem.
Suppose I have an array with data. The numbers are their weight, in percent.:
Ivan => 60
Maxim => 20
Vova => 20
Answer the question
In order to leave comments, you need to log in
The second option is what you need. It remains to get a random from 0 to 4 (with a uniform distribution) and take resp. name. Ivan has just 3/5 chances.
Upd.
function getRandomWinner($ppl)
{
$choice = rand(0, array_sum(array_values($ppl)) - 1);
$sum = 0;
foreach($ppl as $name => $rank) {
$sum += $rank;
if ($choice < $sum) return $name;
}
}
$winnerName = getRandomWinner([
'Иван' => 60,
'Максим' => 20,
'Вова' => 20,
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question