你在正确的路线上。在此处的另一个 StackOverflow 答案中详细介绍了一个很好的算法。
您的实现可能如下所示:
function getWeightedRandom(array $options) {
// calculate the total of all weights
$combined = array_sum($options);
// generate a random number, where 0 <= $random < $combined
$random = rand(0, $combined - 1);
// keep subtracting weights until we drop below an option's weight
foreach($options as $name => $weight) {
if($random < $weight) {
return $name;
}
$random -= $weight;
}
}
// the weights to use for our trials (do not have to add up to 100)
$gender = array(
'Male' => 30,
'Female' => 50,
'U' => 20);
// used for keeping track of how many of each result
$results = array(
'Male' => 0,
'Female' => 0,
'U' => 0);
// run a large number of trials to properly test our accuracy
for($i = 0; $i < 100000; $i++) {
$result = getWeightedRandom($gender);
$results[$result]++;
}
print_r($results);
输出:
Array
(
[Male] => 30013
[Female] => 49805
[U] => 20182
)
在我看来还不错!