赞
踩
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。