Java中的随机加权选择 [英] Random weighted selection in Java

查看:29
本文介绍了Java中的随机加权选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个集合中随机选择一个项目,但选择任何项目的机会应该与相关的权重成正比

示例输入:

物品重量---- ------苦难之剑 10快乐之盾5死亡药水 6三刃剑1

所以,如果我有 4 种可能的物品,那么获得任何一件没有重量的物品的几率是四分之一.

在这种情况下,用户获得痛苦之剑的可能性应该是三刃剑的 10 倍.

如何在 Java 中进行加权随机选择?

解决方案

我会使用 NavigableMap

公共类RandomCollection{private final NavigableMap<Double, E>map = new TreeMap();private final Random 随机;私人双倍总数 = 0;公共随机集合(){这(新随机());}公共 RandomCollection(随机随机){this.random = 随机;}公共 RandomCollection<E>添加(双倍权重,E 结果){if (weight <= 0) 返回这个;总+=重量;map.put(total, result);返回这个;}公共 E 下一个(){双值 = random.nextDouble() * total;返回 map.higherEntry(value).getValue();}}

<块引用>

假设我有一个概率分别为 40%、35%、25% 的动物狗、猫、马的列表

RandomCollectionrc = 新的 RandomCollection().add(40, "dog").add(35, "cat").add(25, "horse");for (int i = 0; i <10; i++) {System.out.println(rc.next());}

I want to choose a random item from a set, but the chance of choosing any item should be proportional to the associated weight

Example inputs:

item                weight
----                ------
sword of misery         10
shield of happy          5
potion of dying          6
triple-edged sword       1

So, if I have 4 possible items, the chance of getting any one item without weights would be 1 in 4.

In this case, a user should be 10 times more likely to get the sword of misery than the triple-edged sword.

How do I make a weighted random selection in Java?

解决方案

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();
    }
}

Say I have a list of animals dog, cat, horse with probabilities as 40%, 35%, 25% respectively

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中的随机加权选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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