Skip to content

Instantly share code, notes, and snippets.

@hskrasek
Created November 10, 2016 22:19
Show Gist options
  • Save hskrasek/b6684ae4f9f3cca9b18bc831071fbbc7 to your computer and use it in GitHub Desktop.
Save hskrasek/b6684ae4f9f3cca9b18bc831071fbbc7 to your computer and use it in GitHub Desktop.
Randomly selects a value from from the collection, by weight.
<?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;
}
}
});
@adamwathan
Copy link

adamwathan commented Nov 11, 2016

Think this would do it too!

Collection::macro('weightedRandom', function () {
    return $this->flatMap(function ($weight, $value) {
        return collect(range(1, $weight))->map(function () use ($value) {
            return $value;
        });
    })->random(); 
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment