首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中按权重生成随机结果?

在PHP中按权重生成随机结果?
EN

Stack Overflow用户
提问于 2009-01-15 00:44:38
回答 9查看 34.9K关注 0票数 72

我知道如何在PHP中生成一个随机数,但假设我想要一个介于1-10之间的随机数,但我想要更多的3,4,5,然后是8,9,10,这怎么可能?我会发布我已经尝试过的东西,但老实说,我甚至不知道从哪里开始。

EN

回答 9

Stack Overflow用户

发布于 2012-08-09 04:48:03

基于@Allain的answer/link,我用PHP编写了这个快速函数。如果要使用非整数加权,则必须对其进行修改。

代码语言:javascript
复制
  /**
   * getRandomWeightedElement()
   * Utility function for getting random values with weighting.
   * Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)
   * An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
   * The return value is the array key, A, B, or C in this case.  Note that the values assigned
   * do not have to be percentages.  The values are simply relative to each other.  If one value
   * weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
   * chance of being selected.  Also note that weights should be integers.
   * 
   * @param array $weightedValues
   */
  function getRandomWeightedElement(array $weightedValues) {
    $rand = mt_rand(1, (int) array_sum($weightedValues));

    foreach ($weightedValues as $key => $value) {
      $rand -= $value;
      if ($rand <= 0) {
        return $key;
      }
    }
  }
票数 113
EN

Stack Overflow用户

发布于 2010-05-20 03:24:10

This tutorial通过多个剪切和粘贴解决方案,用PHP语言向您介绍了整个过程。请注意,由于下面的注释,此例程对您在该页面上找到的内容进行了轻微修改。

从post中获取的函数:

代码语言:javascript
复制
/**
 * weighted_random_simple()
 * Pick a random item based on weights.
 *
 * @param array $values Array of elements to choose from 
 * @param array $weights An array of weights. Weight must be a positive number.
 * @return mixed Selected element.
 */

function weighted_random_simple($values, $weights){ 
    $count = count($values); 
    $i = 0; 
    $n = 0; 
    $num = mt_rand(1, array_sum($weights)); 
    while($i < $count){
        $n += $weights[$i]; 
        if($n >= $num){
            break; 
        }
        $i++; 
    } 
    return $values[$i]; 
}
票数 7
EN

Stack Overflow用户

发布于 2016-06-24 15:26:11

代码语言:javascript
复制
/**
 * @param array $weightedValues
 * @return string
 */
function getRandomWeightedElement(array $weightedValues)
{
    $array = array();

    foreach ($weightedValues as $key => $weight) {
        $array = array_merge(array_fill(0, $weight, $key), $array);
    }

    return $array[array_rand($array)];
}

getRandomWeightedElement(array('A'=>10, 'B'=>90));

这是一个非常简单的方法。如何获得随机加权元素。我填充数组变量$key。我让$key去数组$weight x,然后用array_rand去数组。并且我有随机值;)。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/445235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档