说明:
在阅读源码时发现了一段实现随机选择器的代码,感觉不错,现分享出来。
public class RandomSelector {
private final NavigableMap<Integer, Object> map = new TreeMap<>();
private Integer total = 0;
Random random = new Random();
public void addItem(Integer weight, Object item) {
if (weight != null && weight > 0) {
total += weight;
map.put(total, item);
}
}
public Object get() {
Integer randomInt = random.nextInt(total);
return map.higherEntry(randomInt).getValue();
}
public static void main(String[] args) {
RandomSelector randomSelector = new RandomSelector();
randomSelector.addItem(40,"a");
randomSelector.addItem(60,"b");
int a = 0;
int b = 0;
for (int i = 0; i < 10000; i++) {
Object val = randomSelector.get();
if ("a".equals(val)){
a++;
}else if ("b".equals(val)){
b++;
}
}
System.out.println(String.format("a:%s b:%s",a,b));
}
}
注意:
代码务必要多敲,就上面这么简单的一段代码,我自己敲错了好多地方。🤣