根据概率抽奖(无奖品数量) -- Java实现

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());
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值