根據概率抽獎(無獎品數量) -- Java實現
阿新 • • 發佈:2019-02-17
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", newBigDecimal(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()); } } }