Created
September 14, 2012 08:56
-
-
Save rickydunlop/3720869 to your computer and use it in GitHub Desktop.
Weighted number generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Number generator | |
* | |
* Generates random numbers with weighting. | |
* Pass in an associative array, such as | |
* | |
* array( | |
* 'A' => 10, // 10% chance | |
* 'B' => 30, // 30% chance | |
* 'C' => 60 // 60% chance | |
* ); | |
* | |
* Values are relative to each other, for example if the weights were 5 and 10, | |
* The value with the weight of 10 is twice as likely to be selected. | |
* | |
* Example usage: | |
* $generator = new NumberGenerator(); | |
* $generator->weightedValues = array( | |
* '50% off' => '5', | |
* '25% off' => '10', | |
* '20% off' => '15', | |
* '10% off' => '30', | |
* '5% off' => '40' | |
* ); | |
* echo $generator->getWeightedRandom(); | |
* | |
* @author Ricky Dunlop <[email protected]> | |
**/ | |
class NumberGenerator { | |
public $weightedValues = array(); | |
/** | |
* Generates a random number which is lower than the sum of the weights | |
* Loops through array of weights subtracting the weights from the random number | |
* in order until the random number is negative then returns the key | |
* | |
* @param array $weightedValues | |
*/ | |
public function getWeightedRandom() { | |
$rand = mt_rand(1, (int) array_sum($this->weightedValues)); | |
foreach ($this->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