Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking random item from PHP array based on probability

Tags:

php

I have a map of users and a count of entries/tickets they have purchased for a raffle (or lottery or any other similar event).

The map of users to entries is in the structure as seen below:

// Map the person to the amount of entries they have purchased
$entries = [
    'Adam' => 5,
    'James' => 3,
    'Oliver' => 4,
    'Holly' => 8
];

I want to choose a random user but take into consideration their chance based on ticket count. The probability of winning must be:

(User Ticket Amount / Total Ticket Count) * 100 = Probability percentage

For example, from the test array the expected results is Holly will win the raffle 8 times out of 20 times.

like image 265
Adam Zorchubiez Avatar asked Mar 03 '23 01:03

Adam Zorchubiez


1 Answers

It's a coincidence you are asking this as I created a method to do just this the other day when writing a script for a betting site.

Please see the comments for explanation of what the code consists of:

// The array passed to the function should be your $entries array
function randProb(array $items) {
  $totalProbability = 0; // This is defined to keep track of the total amount of entries

  foreach ($items as $item => $probability) {
      $totalProbability += $probability;     
  }

  $stopAt = rand(0, $totalProbability); // This picks a random entry to select
  $currentProbability = 0; // The current entry count, when this reaches $stopAt the winner is chosen

  foreach ($items as $item => $probability) { // Go through each possible item
      $currentProbability += $probability; // Add the probability to our $currentProbability tracker
      if ($currentProbability >= $stopAt) { // When we reach the $stopAt variable, we have found our winner
          return $item;
      }
  }

  return null;
}

Any questions feel free to ask below, if you would like to output the value (probability) of the winning item, return $probability at the breakpoint instead of $item

like image 118
Josh Wood Avatar answered Mar 05 '23 15:03

Josh Wood