我在几个PHP游戏引擎中使用了此功能:
<?phpfunction 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];
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)