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