如何根据概率选择一个项目? [英] 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屋!