Created
November 10, 2016 22:19
-
-
Save hskrasek/b6684ae4f9f3cca9b18bc831071fbbc7 to your computer and use it in GitHub Desktop.
Randomly selects a value from from the collection, by weight.
This file contains 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 | |
/** | |
* Returns a random item from the collection based on a weighted value. | |
* ['foo' => 70, 'bar' => 30] Foo has a 70 percent chance of being returned | |
* @return int|string | |
*/ | |
Collection::macro('weightedRandom', function () { | |
$sumOfWeights = $this->sum(); | |
$rand = rand(1, $sumOfWeights); | |
foreach ($this as $value => $weight) { | |
$rand -= $weight; | |
if ($rand <= 0) { | |
return $value; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Think this would do it too!