Home >Backend Development >PHP Tutorial >How to Generate Weighted Random Numbers in PHP?
Weighted Random Number Generation in PHP
Question:
How can you generate random numbers between 1 and 10, but with a higher probability of selecting numbers 3, 4, and 5 compared to 8, 9, and 10 in PHP?
Answer:
To achieve this weighted randomness, you can utilize an associative array that maps each desired outcome to its weight. In this case, you can create an array where 3, 4, and 5 have higher weights (e.g., 3 - 50%, 4 - 30%, 5 - 20%) than 8, 9, and 10 (e.g., 8 - 10%, 9 - 5%, 10 - 5%).
Based on the weights assigned, you can generate a random number using mt_rand within the range of the total sum of weights. Then, loop through the array and subtract each weight value from the random number until it becomes negative. The array key corresponding to the weight that makes the random number negative is the desired outcome.
Here's a PHP function that implements this weighted randomness:
/** * getRandomWeightedElement() * Utility function for getting random values with weighting. * Pass in an associative array, such as array('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) { $rand = mt_rand(1, (int) array_sum($weightedValues)); foreach ($weightedValues as $key => $value) { $rand -= $value; if ($rand <= 0) { return $key; } } }
The above is the detailed content of How to Generate Weighted Random Numbers in PHP?. For more information, please follow other related articles on the PHP Chinese website!