K
K
KarambiG2021-08-05 22:19:45
PHP
KarambiG, 2021-08-05 22:19:45

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


And the task arose to select a random element depending on its weight. For example, the chance that the element "john" will be selected is greater than the others. Because it has more weight.
Tell me how to be?..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-08-05
@KarambiG

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 question

Ask a Question

731 491 924 answers to any question