import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @PACKAGE_NAME.Test * 日期: 2017/5/3 * 描述: */ public class Test { /** * 所有所有奖品 */ public enum Trophy { A("奖品-A", new BigDecimal(0.889)), B("奖品-B", new BigDecimal(0.1)), C("奖品-C", new BigDecimal(0.01)), D("奖品-D", new BigDecimal(0.001)),; public String name; public BigDecimal probably; Trophy(String name, BigDecimal probably) { this.name = name; this.probably = probably; } } /** * 获取一个随机数 * * @param min 最大值 * @param max 最小值 * @return */ public int getRandomInt(int min, int max) { return (int) Math.round(Math.random() * (max - min) + min); } /** * 获取随机数的最大值 * * @param trophies 所有奖品 * @return */ public int getMaxRandomInt(List<Trophy> trophies) { BigDecimal minProbably = trophies.stream().min((x, y) -> x.probably.compareTo(y.probably)).get().probably; String[] split = (minProbably.doubleValue() + "").trim().split("\\."); return (int) Math.pow(10, split[split.length - 1].length()); } /** * 抽奖 * * 随机一个数,判断在哪个奖品的区间内 * * @return */ public Trophy draw() { Trophy trophy = null; int maxInt = getMaxRandomInt(Arrays.asList(Trophy.values())); int random = getRandomInt(1, maxInt), start = 0; for (Trophy trophy1 : Trophy.values()) { int end = start + (int) (trophy1.probably.doubleValue() * maxInt); if (random > start && random <= end) { trophy = trophy1; break; } else { start = end; } } return trophy; } @org.junit.Test public void test() { List<Trophy> trophyList = new ArrayList<>(); for (int i = 0; i < 10000; i++) { Trophy trophy = draw(); if (trophy != null) { trophyList.add(trophy); } } //计算各个抽中次数 for (Trophy trophy : Trophy.values()) { System.out.println("抽中 " + trophy.name + " 数量:" + trophyList.stream().filter(trophy1 -> trophy1.equals(trophy)).count()); } } }
根据概率抽奖(无奖品数量) -- Java实现
最新推荐文章于 2024-04-30 17:01:13 发布