本文介绍了Java中的随机加权选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从一组中选择一个随机项目,但是选择任何项目的机会应该与相关权重成正比。
I want to choose a random item from a set, but the chance of choosing any item should be proportional to the associated weight
示例输入:
item weight
---- ------
sword of misery 10
shield of happy 5
potion of dying 6
triple-edged sword 1
所以,如果我有4个可能的项目,获得任何一个没有权重的项目的机会将是1/4。
So, if I have 4 possible items, the chance of getting any one item without weights would be 1 in 4.
在这种情况下,用户应该是10倍获得与三刃剑相当的痛苦之剑。
In this case, a user should be 10 times more likely to get the sword of misery than the triple-edged sword.
如何在Java中进行加权随机选择?
How do I make a weighted random selection in Java?
推荐答案
我将使用NavigableMap
I would use a NavigableMap
public class RandomCollection<E> {
private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
private final Random random;
private double total = 0;
public RandomCollection() {
this(new Random());
}
public RandomCollection(Random random) {
this.random = random;
}
public RandomCollection<E> add(double weight, E result) {
if (weight <= 0) return this;
total += weight;
map.put(total, result);
return this;
}
public E next() {
double value = random.nextDouble() * total;
return map.higherEntry(value).getValue();
}
}
RandomCollection<String> rc = new RandomCollection<>()
.add(40, "dog").add(35, "cat").add(25, "horse");
for (int i = 0; i < 10; i++) {
System.out.println(rc.next());
}
这篇关于Java中的随机加权选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!