I have an array with values and probabilities (or in PHP, keys and values):
Value Probability
John 3
Peter 2
Paul 1
I want to shuffle this array but have the order be influenced by the probability. That is, on average John should appear at the top of the list half the time, Peter a third of the time, and Paul one sixth of the time. The average order over thousands of shuffles should be the one given above.
I have thought to
-
Create an array in which each value appears as often as indicated by the probability:
John John John Peter Peter Paul -
Shuffle this array, e.g.:
John Paul Peter John John Peter -
Remove the duplicates, leaving the first instance:
John Paul Peter
In PHP code this might look something like this:
$items = array(
'John' => 3,
'Peter' => 2,
'Paul' => 1
);
$probabilities = array();
foreach($items as $item => $value){
$interim = array_fill(1, $value, $item);
$probabilities = array_merge($probabilities, $interim);
}
shuffle($probabilities);
$result = array_unique($probabilities);
print("<pre>".print_r($result,true)."</pre>");
Is there a faster way to do this?
The real array contains a few hundred values and this probability-based shuffling has to be done everytime a webpage is called, so it should be lightning quick.