Java中的随机加权选择

时间:2011-06-20 10:06:54

标签: java random double

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

示例输入:

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

所以,如果我有4个可能的项目,那么获得任何一个没有权重的项目的机会将是1/4。

在这种情况下,使用者获得痛苦之剑的可能性应该是三角剑的10倍。

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

7 个答案:

答案 0 :(得分:98)

我会使用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();
    }
}
  

说我有动物狗,猫,马的列表,概率分别为40%,35%,25%

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

答案 1 :(得分:23)

您将找不到此类问题的框架,因为所请求的功能仅仅是一个简单的功能。做这样的事情:

interface Item {
    double getWeight();
}

class RandomItemChooser {
    public Item chooseOnWeight(List<Item> items) {
        double completeWeight = 0.0;
        for (Item item : items)
            completeWeight += item.getWeight();
        double r = Math.random() * completeWeight;
        double countWeight = 0.0;
        for (Item item : items) {
            countWeight += item.getWeight();
            if (countWeight >= r)
                return item;
        }
        throw new RuntimeException("Should never be shown.");
    }
}

答案 2 :(得分:16)

现在在Apache Commons中有一个类:EnumeratedDistribution

Item selectedItem = new EnumeratedDistribution(itemWeights).sample();

其中itemWeightsList<Pair<Item,Double>>,就像(在Arne的回答中假设Item接口):

List<Pair<Item,Double>> itemWeights = Collections.newArrayList();
for (Item i : itemSet) {
    itemWeights.add(new Pair(i, i.getWeight()));
}

或Java 8:

itemSet.stream().map(i -> new Pair(i, i.getWeight())).collect(toList());

注意:Pair此处必须为org.apache.commons.math3.util.Pair,而不是org.apache.commons.lang3.tuple.Pair

答案 3 :(得分:4)

使用别名方法

如果您要滚动很多次(如在游戏中),则应使用别名方法。

下面的代码实际上是这种别名方法的相当长的实现。但这是因为初始化部分。元素的检索速度非常快(请参阅nextapplyAsInt方法,它们不会循环播放。

用法

Set<Item> items = ... ;
ToDoubleFunction<Item> weighter = ... ;

Random random = new Random();

RandomSelector<T> selector = RandomSelector.weighted(items, weighter);
Item drop = selector.next(random);

实施

此实施:

  • 使用 Java 8 ;
  • 旨在尽可能快地 (好吧,至少,我尝试使用微基准测试);
  • 完全线程安全(在每个帖子中保留一个Random以获得最佳性能,使用ThreadLocalRandom?);
  • 获取O(1)中的元素,与您在Internet或StackOverflow上找到的元素不同,其中天真实现在O(n)或O(log(n))中运行;
  • 使项目与其重量无关,因此可以在不同的上下文中为项目分配不同的权重。

无论如何,这里是代码。 (请注意I maintain an up to date version of this class。)

import static java.util.Objects.requireNonNull;

import java.util.*;
import java.util.function.*;

public final class RandomSelector<T> {

  public static <T> RandomSelector<T> weighted(Set<T> elements, ToDoubleFunction<? super T> weighter)
      throws IllegalArgumentException {
    requireNonNull(elements, "elements must not be null");
    requireNonNull(weighter, "weighter must not be null");
    if (elements.isEmpty()) { throw new IllegalArgumentException("elements must not be empty"); }

    // Array is faster than anything. Use that.
    int size = elements.size();
    T[] elementArray = elements.toArray((T[]) new Object[size]);

    double totalWeight = 0d;
    double[] discreteProbabilities = new double[size];

    // Retrieve the probabilities
    for (int i = 0; i < size; i++) {
      double weight = weighter.applyAsDouble(elementArray[i]);
      if (weight < 0.0d) { throw new IllegalArgumentException("weighter may not return a negative number"); }
      discreteProbabilities[i] = weight;
      totalWeight += weight;
    }
    if (totalWeight == 0.0d) { throw new IllegalArgumentException("the total weight of elements must be greater than 0"); }

    // Normalize the probabilities
    for (int i = 0; i < size; i++) {
      discreteProbabilities[i] /= totalWeight;
    }
    return new RandomSelector<>(elementArray, new RandomWeightedSelection(discreteProbabilities));
  }

  private final T[] elements;
  private final ToIntFunction<Random> selection;

  private RandomSelector(T[] elements, ToIntFunction<Random> selection) {
    this.elements = elements;
    this.selection = selection;
  }

  public T next(Random random) {
    return elements[selection.applyAsInt(random)];
  }

  private static class RandomWeightedSelection implements ToIntFunction<Random> {
    // Alias method implementation O(1)
    // using Vose's algorithm to initialize O(n)

    private final double[] probabilities;
    private final int[] alias;

    RandomWeightedSelection(double[] probabilities) {
      int size = probabilities.length;

      double average = 1.0d / size;
      int[] small = new int[size];
      int smallSize = 0;
      int[] large = new int[size];
      int largeSize = 0;

      // Describe a column as either small (below average) or large (above average).
      for (int i = 0; i < size; i++) {
        if (probabilities[i] < average) {
          small[smallSize++] = i;
        } else {
          large[largeSize++] = i;
        }
      }

      // For each column, saturate a small probability to average with a large probability.
      while (largeSize != 0 && smallSize != 0) {
        int less = small[--smallSize];
        int more = large[--largeSize];
        probabilities[less] = probabilities[less] * size;
        alias[less] = more;
        probabilities[more] += probabilities[less] - average;
        if (probabilities[more] < average) {
          small[smallSize++] = more;
        } else {
          large[largeSize++] = more;
        }
      }

      // Flush unused columns.
      while (smallSize != 0) {
        probabilities[small[--smallSize]] = 1.0d;
      }
      while (largeSize != 0) {
        probabilities[large[--largeSize]] = 1.0d;
      }
    }

    @Override public int applyAsInt(Random random) {
      // Call random once to decide which column will be used.
      int column = random.nextInt(probabilities.length);

      // Call random a second time to decide which will be used: the column or the alias.
      if (random.nextDouble() < probabilities[column]) {
        return column;
      } else {
        return alias[column];
      }
    }
  }
}

答案 4 :(得分:1)

public class RandomCollection<E> {
  private final NavigableMap<Double, E> map = new TreeMap<Double, E>();
  private double total = 0;

  public void add(double weight, E result) {
    if (weight <= 0 || map.containsValue(result))
      return;
    total += weight;
    map.put(total, result);
  }

  public E next() {
    double value = ThreadLocalRandom.current().nextDouble() * total;
    return map.ceilingEntry(value).getValue();
  }
}

答案 5 :(得分:1)

如果您在选择后需要删除元素,则可以使用其他解决方案。将所有元素添加到'LinkedList'中,每个元素必须按重量添加多次,然后使用Collections.shuffle(),根据JavaDoc

  

使用默认的随机源随机置换指定的列表。所有排列都以大致相等的可能性发生。

最后,使用pop()removeFirst()

获取和删除元素
Map<String, Integer> map = new HashMap<String, Integer>() {{
    put("Five", 5);
    put("Four", 4);
    put("Three", 3);
    put("Two", 2);
    put("One", 1);
}};

LinkedList<String> list = new LinkedList<>();

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    for (int i = 0; i < entry.getValue(); i++) {
        list.add(entry.getKey());
    }
}

Collections.shuffle(list);

int size = list.size();
for (int i = 0; i < size; i++) {
    System.out.println(list.pop());
}

答案 6 :(得分:0)

139

有一个简单的算法可以随机选择一件物品,其中物品具有各自的权重:

  1. 计算所有权重之和

  2. 选择一个0或更大且小于权重之和的随机数

  3. 一次浏览一个项目,从您的随机数中减去它们的权重,直到获得随机数小于该项目权重的项目