Last active
March 9, 2017 14:15
-
-
Save savvot/f8eae60ba8f2fda50a78 to your computer and use it in GitHub Desktop.
Weighted random function
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 | |
/** | |
* @param array $data array of "key => weight" data to get random key from, all weights must be positive integers | |
* @return mixed key from $data array choosen by weighted random | |
*/ | |
function weightRandom(array $data) | |
{ | |
$c = count($data); | |
if (!$c) { | |
return false; | |
} elseif ($c == 1) { | |
return key($data); | |
} | |
$weight = rand(1, array_sum($data)); | |
foreach ($data as $k => $w) { | |
$weight -= $w; | |
if ($weight <= 0) { | |
return $k; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment