0

I have an array full of items and I have to draw from all of them only one. It's simple, but here there are complications. Each of them has a variable chance of being drawn. The default chance is 1. 0 means that the element will never be selected and 2 means that the element has double chance to be selected.

$elements = array(
    "A" => "1",   // normal chance to be selected   (= 25%)
    "B" => "1",   // normal chance to be selected   (= 25%)
    "C" => "2",   // double chance to be selected   (= 50%)
    "D" => "0"    // no chance to be selected       (= 0%)
)

This is only simple example, but my appropriate array has 2000+ elements and chance from 0 to 20.

What is the best way to do that?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
ZaquPL
  • 789
  • 2
  • 12
  • 28
  • 1
    possible duplicate of [Generating random results by weight in PHP?](http://stackoverflow.com/questions/445235/generating-random-results-by-weight-in-php) – Peter O. Aug 30 '14 at 14:27
  • @Peter O. And this is solution. Sorry for duplicate. – ZaquPL Aug 30 '14 at 23:03

1 Answers1

1

One simple way is to transform this data array into an array that contains each element the given number of times, and then use array_rand() to pick from it. Given your example, if you transform it to an array("A", "B", "C", "C") then you get the required probabilities.

Here's some code to do that transformation:

function pickFromArray($elements) { 
    $optionsPool = [];
    foreach ($elements as $item => $occurrences) { 
        for ($i = 0; $i < $occurrences; $i++) { 
            $optionsPool[] = $item;
        }
    }
    return $optionsPool[array_rand($optionsPool)];
}
Alex P
  • 5,942
  • 2
  • 23
  • 30