从数组返回一个随机值的概率成正比,它的价值 [英] Returning a random value from array with probability proportional to it's value

查看:167
本文介绍了从数组返回一个随机值的概率成正比,它的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

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

欲随机选择来自阵列的密钥中的一个。但是概率分布应使得拾取元件的概率应该正比于它的数值。

I want to randomly pick one of the "Key" from the array. However the probability distribution should be such that probability of picking an element should be proportional to it's value.

推荐答案

添加所有的值(10 + 2 + 12 24);获得在范围[0,24)的随机数,并挑选取决于数目是否位于在[0,10)中的相应元素,[10,12),或[12,24)。

Add all values (10+2+12 is 24); get a random number in the range [0, 24), and pick the corresponding element depending on whether the number lies in [0, 10), [10, 12), or [12, 24).

这篇关于从数组返回一个随机值的概率成正比,它的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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