java简单抽奖

@Test
    public void test1() {
        //{"list":[{"integral":500,"probability":80},{"integral":100,"probability":8},{"integral":160,"probability":4},{"integral":110,"probability":6},{"integral":190,"probability":2}],"lotteryIntegral":20}
        RotaryDriveOutVO rotaryDrive = activityMainService.getRotaryDrive(ActivitySubEnum.ROTARY_PRIZE.getCode());
        List<IntegralProbability> list = rotaryDrive.getList();
        Map<Integer, Integer> map = new TreeMap<>();
        int a = 0;
        for (IntegralProbability integralProbability : list) {
            if (a == 0) {
                a = integralProbability.getProbability();
            } else {
                a += integralProbability.getProbability();
            }
            map.put(integralProbability.getIntegral(), a);
        }
        System.out.println(JSON.toJSONString(map));


        List<Map.Entry<Integer, Integer>> mapList = new ArrayList<>(map.entrySet());
        //利用Collections的sort方法对list排序
        mapList.sort(Comparator.comparingInt(Map.Entry::getValue));

        System.out.println("排序之后:" + JSON.toJSONString(mapList));

        Random random = new Random();
        int r = random.nextInt(99) + 1;
        System.out.println("标枪:" + r);

        for (Map.Entry<Integer, Integer> entry : mapList) {
            if (entry.getValue() >= r) {
                Integer key = entry.getKey();
                System.out.println("抽中了 " + key);
                break;
            }
        }
    }

思路:区间落点,就像打靶一样,我这里是抽积分,要是抽别的可以把奖品id放到key里面,其实也可以不用排序,使用TreeMap的默认key排序,但是概率要放到key里面了,我这里是手动排序了一下。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值