根据用户定义的权重选择随机元素
问题内容:
我有一个Web应用程序,用户可以在其中添加1到20个文本字符串,并为其分配显示频率。然后,系统将基于定义的权重选择一个随机字符串。最好的方法是什么?每个琴弦的重量范围值重要吗?我可以让用户为每个字符串分配一个数字(0-100)吗?您将如何选择随机字符串?(每个选择都不必担心之前选择的内容,每个字符串在每次调用开始时被选择的几率相同(基于权重))。
问题答案:
我在几个PHP游戏引擎中使用了此功能:
<?php
/**
* @param array $values - just the weights
* @return integer A number between 0 and count($values) - 1
*/
function getBucketFromWeights($values) {
$total = $currentTotal = $bucket = 0;
$firstRand = mt_rand(1, 100);
foreach ($values as $amount) {
$total += $amount;
}
$rand = ($firstRand / 100) * $total;
foreach ($values as $amount) {
$currentTotal += $amount;
if ($rand > $currentTotal) {
$bucket++;
}
else {
break;
}
}
return $bucket;
}
用法
假设我在一个关联数组中具有用户权重,其中每个字符串都指向其权重:
$weighted_strings = array(
"important string" => 100,
"terrible string" => 10,
"never string" => 0,
// etc
);
如果我想根据重量拉一根绳子,可以这样做:
$weights = array_values($weighted_strings);
$strings = array_keys($weighted_strings);
$index = getBucketFromWeights($weights);
$selectedString = $strings[$index];