从数组中返回一个随机值,其概率与其值成比例

时间:2011-11-26 18:14:16

标签: php arrays random probability

我有一个类似

的数组
$keywords = array('apple'=>10,'orange'=>2,'grape'=>12); 

我想从数组中随机选择一个“Key”。然而,概率分布应该使得挑选元素的概率应该与其值成比例。

3 个答案:

答案 0 :(得分:16)

添加所有值(10 + 2 + 12为24);得到[0,24]范围内的随机数,并根据数字是在[0,10],[10,12]还是[12,24]中选择相应的元素。

答案 1 :(得分:1)

我这样做:

    $probabilities = array('apple'=>50, 'orange'=>20, 'banana'=>10);

    function random_probability($probabilities) {
      $rand = rand(0, array_sum($probabilities));
      do {
        $sum = array_sum($probabilities);
        if($rand <= $sum && $rand >= $sum - end($probabilities)) {
          return key($probabilities);
        }
      } while(array_pop($probabilities));
    }

答案 2 :(得分:0)

O(log(n))方法(直接从answer to a very similar question翻录):

通常的技术是将数组转换为累积和数组:

 [10 60 5 25]  --> [10 70 75 100]

选择从零到累计总数的范围内的随机数(在示例中为0 <= x < 100)。然后,在累积数组上使用bisection将索引定位到原始数组中:

Random variable x      Index in the Cumulative Array      Value in Original Array
-----------------      -----------------------------      ----------------------
 0 <= x < 10                      0                            10
10 <= x < 70                      1                            60
70 <= x < 75                      2                             5
75 <= x < 100                     3                            25 

例如,如果随机变量 x 为4,则将累积数组二等分给出位置索引0,其对应于原始数组中的10。

并且,如果随机变量 x 是72,则将累积数组二等分给出位置索引2,其对应于原始数组中的5。