Last active
August 29, 2015 14:24
-
-
Save tokubass/ee363d410e8a18adaecc to your computer and use it in GitHub Desktop.
random_picker
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 | |
function make_random_picker ($item_list,$weight_list) { | |
$total_weight = array_sum($weight_list); | |
$weighted_array = array_combine($item_list,$weight_list); | |
arsort($weighted_array); | |
return function () use (&$total_weight, &$weighted_array) { | |
$p = 0; | |
$r = mt_rand(1,$total_weight); | |
foreach ($weighted_array as $key => $value) { | |
$p += $value; | |
if ($r <= $p) { | |
return $key; | |
} | |
} | |
}; | |
} | |
$c = make_random_picker( | |
['db2','db1','db3'], | |
[25,50,25] | |
); | |
$test = ['db1' => 0, 'db2' => 0, 'db3' => 0]; | |
foreach(range(1,100000) as $i){ | |
$test[$c()]++; | |
} | |
print_r($test); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment