三个杯子藏糖,选择一个杯子。 其他两个随机翻开一个,如果没有糖,选择另外一个杯子。计算最终概率。
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;
}
}