当前位置:   article > 正文

java 权重_Java 基于权重按比例分配算法

java 比例分配算法

public class WeightRandomStrategy {

private TreeMap weightMap = new TreeMap<>();

public WeightRandomStrategy(List> list) {

for (Pair 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 tailMap = this.weightMap.tailMap(randomWeight, false);

return this.weightMap.get(tailMap.firstKey());

}

}

List> list = new ArrayList<>();

list.add(new ImmutablePair<>("TR", 90));

list.add(new ImmutablePair<>("TX", 10));

WeightRandomStrategy 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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/289220?site
推荐阅读
相关标签
  

闽ICP备14008679号