Java 基于权重按比例分配算法

public class WeightRandomStrategy<K, V extends Number> {
    private TreeMap<Double, K> weightMap = new TreeMap<>();

    public WeightRandomStrategy(List<Pair<K, V>> list) {
        for (Pair<K, V> pair : list) {
            double lastWeight = this.weightMap.size() == 0 ? 0 : this.weightMap.lastKey();
            this.weightMap.put(pair.getValue().doubleValue() + lastWeight, pair.getKey());
        }
    }

    public K random() {
        double randomWeight = this.weightMap.lastKey() * Math.random();
        SortedMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false);
        return this.weightMap.get(tailMap.firstKey());
    }
}
List<Pair<String, Integer>> list = new ArrayList<>();
list.add(new ImmutablePair<>("TR", 90));
list.add(new ImmutablePair<>("TX", 10));
WeightRandomStrategy<String, Integer> strategy = new WeightRandomStrategy<>(list);
int a = 0, b = 0;
for (int i = 0; i < 10000; i++) {
    switch (strategy.random()) {
        case "TR":
            a++;
            break;
        case "TX":
            b++;
            break;
        default:
            break;
    }
}
System.out.println("a=" + a + ", b=" + b);
System.out.println("a+b=" + (a + b));

---------------------------------------------------output
a=8993, b=1007
a+b=10000

本文链接地址:https://dorole.com/2014/

来自:Dorole's Blog

发布者

Steve

编程/摄影

发表评论

电子邮件地址不会被公开。 必填项已用*标注

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: