Skip to content

Instantly share code, notes, and snippets.

@tokubass
Last active August 29, 2015 14:24
Show Gist options
  • Save tokubass/ee363d410e8a18adaecc to your computer and use it in GitHub Desktop.
Save tokubass/ee363d410e8a18adaecc to your computer and use it in GitHub Desktop.
random_picker
<?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