杯子藏糖问题源码

  三个杯子藏糖,选择一个杯子。 其他两个随机翻开一个,如果没有糖,选择另外一个杯子。计算最终概率。

import cn.hutool.core.util.RandomUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wigo.chen
 * @date 2020/2/13 10:40
 * Introduction:
 */
public class FindSugar {
    public static void main(String[] args) {
        //找对次数
        int rightCount = 0;
        //随机1亿次
        int count = 100_000_000;
        for (int i = 0; i < count; i++) {
            //开始藏糖
            Map<Integer, Boolean> CUP = hideSugar();
            //随机选一个杯子
            int num = RandomUtil.randomInt(3);
            //另外两个随机一个杯子
            int cc = randomNum(num);
            //如果翻开的杯子是空,则换杯子
            if(!CUP.get(cc))
                num = exchange(num, cc);
            if(CUP.get(num))
                rightCount++;
        }
        //计算概率
        double ratio = rightCount * 100.0 / count;
        System.out.println(ratio);
    }
    /**
     * 换杯子, 杯子号不能是 num 和 cc
     * */
    private static int exchange(int num, int cc) {
        int n = -1;
        for (int i = 0; i < 3; i++) {
            if(i != num && i != cc)
                n = i;
        }
        return n;
    }
    /**
     * 随机一个杯子, 不能是num
     * */
    private static int randomNum(int num) {
        int n = -1;
        while (true){
            n = RandomUtil.randomInt(3);
            if(n != num)
                break;
        }
        return n;
    }
    /**
     * 准备三个杯子,藏起糖
     * */
    private static Map<Integer, Boolean> hideSugar() {
        //准备三个杯子
        Map<Integer, Boolean> CUP = new HashMap(){{
            put(0, false);
            put(1, false);
            put(2, false);
        }};
        //随机藏糖的杯子序号
        int num = RandomUtil.randomInt(3);
        CUP.put(num, true);
        return CUP;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值