Sometimes you will want to get a random value form an array in a biased random way, that is, you will want certain values to be returned more than others. Here is a function that will generate a single key from an array, with a greater change of a higher value being retrieved.
function biasedRandom($numbers){ $total = 0; foreach($numbers as $number=>$weight){ $total += $weight; $distribution[$number] = $total; }; foreach($distribution as $number=>$weights){ if($rand This function is used in the following way. //set up array 'two'=>100, 'three'=>100, 'four'=>500); // get biased random number echo biasedRandom($array); The key that is generated the most by the function is four because it has a higher value than the rest and will therefore 'weigh' a lot more.
0 comments:
Post a Comment