关于抽奖的概率算法


        @Test
        public void test(){
             //0表示谢谢参与
             int index = 0;
             //------奖品-------
             Map<Integer, String> map = new HashMap<>();
             map.put(0, "谢谢参与");
             map.put(1, "一等奖");
             map.put(2, "二等奖");
             map.put(3, "三等奖");
             map.put(4, "四等奖");
             //------奖品对应的概率-------
             List<Double> orignalRates = new ArrayList<Double>();
            orignalRates.add(0.1);//谢谢参与
            orignalRates.add(0.2);//一等奖
            orignalRates.add(0.3);//二等奖
            orignalRates.add(0.3);//三等奖
            orignalRates.add(0.1);//四等奖
            Map<Integer, Integer> count = new HashMap<Integer, Integer>();
            double num = orignalRates.size();
            //计算随机数落在每个区间的次数
            for (int i = 0; i < num; i++) {
                int orignalIndex = lottery(orignalRates);
                Integer value = count.get(orignalIndex);
                count.put(orignalIndex, value == null ? 1 : value + 1);
            }
            System.out.println("============"+count);
            Collection<Integer> countValue = count.values();
            Object[] valueArray = countValue.toArray();
            Arrays.sort(valueArray);
            Integer maxValue = (Integer) valueArray[valueArray.length - 1];
            for (Integer key : count.keySet()) {
                Integer value = count.get(key);
                if (value == maxValue) {
                    index = key;
                    break;
                }
            }
            System.out.println("============"+map.get(index));
        }
    
     public static int lottery(List<Double> rates) {
            if (rates == null || rates.isEmpty()) {
                return -1;
            }
            // 计算总概率
            double sumRate = 0d;
            for (double rate : rates) {
                sumRate += rate;
            }
            // 计算每个物品的概率
            List<Double> sortRates = new ArrayList<Double>();
            Double tempSumRate = 0d;
            for (double rate : rates) {
                tempSumRate += rate;
                sortRates.add(tempSumRate / sumRate);
            }
            //用 Math.random()获取0-1之间的一个随机数,并放入集合中
            double nextDouble = Math.random();
            sortRates.add(nextDouble);
            //集合重新排序
            Collections.sort(sortRates);
            //获取随机数索引,也就是随机数所在的区间
            int i = sortRates.indexOf(nextDouble);
            return i;
        }

猜你喜欢

转载自blog.csdn.net/qq_38410795/article/details/83749694