由用户定义的权重采摘随机元素 [英] Picking random element by user defined weights

查看:148
本文介绍了由用户定义的权重采摘随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/445235/generating-random-results-by-weight-in-php">Generating重量随机的结果在PHP?

我有一个Web应用程序,用户可以添加1-20字符串文本和分配权重多久应该显示他们。该系统将然后选择基于定义的权重随机字符串。什么是去了解这一点的最好方法是什么?执行范围值每串物的重量?我可以让用户分配一个号码(0-100),每串?你会如何​​去选择一个随机字符串? (每个选择不担心被选中在每个呼叫开始什么之前被选中,每串有相同赔率(以重量计))。

I have a web application where users can add 1-20 strings of text and assign a weight to them of how often it should show up. The system would then choose a random string based on the defined weights. What is the best way to go about this? Do the range values for the weight for each string matter? Could I just have the user assign a number (0-100) for each string? How would you go about choosing a random string? (Each choice doesn't worry about what was chosen before, every string has the same odds (based on weight) of being chosen at the start of each call).

推荐答案

我用几个PHP的游戏引擎这个功能:

I use this function in several PHP game engines:

<?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;
}

用法

假设我有一个关联数组用户权重,每个串点,它的重量:

Suppose I have the user weights in an associative array where each string points to its weight:

$weighted_strings = array(
    "important string" => 100,
    "terrible string" => 10,
    "never string" => 0,
    // etc
);

如果我想拉基于重量的字符串,我会做到这一点:

If I wanted to pull a string based on weight, I'd do this:

$weights = array_values($weighted_strings);
$strings = array_keys($weighted_strings);
$index = getBucketFromWeights($weights);
$selectedString = $strings[$index];

这篇关于由用户定义的权重采摘随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆