Skip to content

Instantly share code, notes, and snippets.

@doncadavona
Forked from irazasyed/weight-utility.php
Last active November 18, 2020 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doncadavona/5dae26219702e5ea3916b75af77d4238 to your computer and use it in GitHub Desktop.
Save doncadavona/5dae26219702e5ea3916b75af77d4238 to your computer and use it in GitHub Desktop.
PHP: Utility function for getting random values with weighting.
<?php
/**
* Utility function for getting random values with weighting.
* Pass in an associative array, such as ['A'=> 5, 'B'=> 45, 'C'=> 50].
* An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
* The return value is the array key, A, B, or C in this case. Note that the values assigned
* do not have to be percentages. The values are simply relative to each other. If one value
* weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
* chance of being selected. Also note that weights should be integers.
*
* @param array $weightedValues
*/
function getRandomWeightedElement(array $weightedValues): int {
$rand = mt_rand(1, (int) array_sum($weightedValues));
foreach ($weightedValues as $key => $value) {
$rand -= $value;
if ($rand <= 0) {
return $key;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment