如何按概率选择项目? [英] How to pick an item by its probability?
问题描述
我有一个项目列表。这些项目中的每一项都有自己的概率。
I have a list of items. Each of these items has its own probability.
任何人都可以根据其概率建议选择项目的算法吗?
Can anyone suggest an algorithm to pick an item based on its probability?
推荐答案
因此,每个项目都会存储一个标记其相对概率的数字,例如,如果您有3个项目,那么选择其中两个项目的可能性应该是其他两个项目的两倍。列表将包含:
So with each item store a number that marks its relative probability, for example if you have 3 items one should be twice as likely to be selected as either of the other two then your list will have:
[{A,1},{B,1},{C,2}]
然后对列表的编号求和(即在我们的例子中为4)。
现在生成一个随机数并选择该索引。
int index = rand.nextInt(4);
返回数字,使索引处于正确的范围内。
Then sum the numbers of the list (i.e. 4 in our case). Now generate a random number and choose that index. int index = rand.nextInt(4); return the number such that the index is in the correct range.
Java代码:
class Item {
int relativeProb;
String name;
//Getters Setters and Constructor
}
...
class RandomSelector {
List<Item> items = new List();
Random rand = new Random();
int totalSum = 0;
RandomSelector() {
for(Item item : items) {
totalSum = totalSum + item.relativeProb;
}
}
public Item getRandom() {
int index = rand.nextInt(totalSum);
int sum = 0;
int i=0;
while(sum < index ) {
sum = sum + items.get(i++).relativeProb;
}
return items.get(Math.max(0,i-1));
}
}
这篇关于如何按概率选择项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!