jinzhongyuan
2021-11-10 15:24:05 +08:00
public static void main(String[] args) {
WeightRandom<String> weightRandom = WeightRandom.create();
weightRandom.add("奖品 1", 0.8);
weightRandom.add("奖品 2", 0.2);
weightRandom.add("谢谢参与", 0);
// 统计 (这里用 AtomicInteger 仅仅是因为写起来比较方便,这是一个单线程测试)
Map<String, AtomicInteger> statistics2 = new HashMap<>();
for (int i = 0; i < 1_0; i++) {
String award = weightRandom.next();
System.out.println(award);
statistics2.computeIfAbsent(award, (k) -> new AtomicInteger()).incrementAndGet();
}
statistics2.forEach(
(k, v) -> {
double hit = (double) v.get() / 1_0;
System.out.println(k + ", hit:" + hit);
});
}
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool}</version>
</dependency>
实现概率抽奖,请叫我雷锋