This is really more a question of approach, but I\'m presenting it in php.
Suppose we had a list of four percentages that a give event will occur on iteration.
$arr = array('walk the dog'=>25,'read the paper'=>25,'listen to music'=>50);
$rand = rand(1,100);
$sum = 0;
$action = '';
foreach ($arr as $k => $v) {
$sum .= $k;
if ($sum <= $k)
$action = $v;
}
Removed those with a key value of zero, and multiplied the key-value with 100 to make it more readable.
Have you considered using the percentage values as a cumulative number?
$array = array('walk the dog'=>.25,'read the paper'=>.25,'drink coffee'=>.0,'listen to music'=>.50);
$rand = rand();
$cur = 0;
foreach ($key=>$val in $array) {
$cur += $val;
if ($rand <= $cur)
return $key;
}
This assumes the values in the array add up to 1. Ordering doesn't matter either...
I'd do something like:
$arr = array (
'walk the dog' => array('min' => 0, 'max' => 25),
'read the paper' => array('min' => 25, 'max' => 50),
'drink coffee' => array('min' => 0, 'max' => 0),
'listen to music' => array('min' => 50, 'max' => 100),
);
$rnd = rand(1,100);
foreach($arr as $k =>$v) {
if ($rnd > $v['min'] && $rnd <= $v['max']) {
echo $k,"\n";
}
}
You can restructure the array in such a way that the events are stored with decreasing probability (for performance) and the value corresponding to an event is the probability of this particular event plus the value of a previous element (which means that the last element will always have the value 1.).
Then you just iterate over the array and return the event for which its value is greater than $rand.