cdsatrian

getRandomWeightedElement function

Mar 5th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.93 KB | None | 0 0
  1.  /**
  2.    * getRandomWeightedElement()
  3.    * Utility function for getting random values with weighting.
  4.    * Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)
  5.    * An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
  6.    * The return value is the array key, A, B, or C in this case.  Note that the values assigned
  7.    * do not have to be percentages.  The values are simply relative to each other.  If one value
  8.    * weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
  9.    * chance of being selected.  Also note that weights should be integers.
  10.    *
  11.    * @param array $weightedValues
  12.    */
  13.   function getRandomWeightedElement(array $weightedValues) {
  14.     $rand = mt_rand(1, (int) array_sum($weightedValues));
  15.  
  16.     foreach ($weightedValues as $key => $value) {
  17.       $rand -= $value;
  18.       if ($rand <= 0) {
  19.         return $key;
  20.       }
  21.     }
  22.   }
Add Comment
Please, Sign In to add comment