首先附三门问题题目和连接https://baike.baidu.com/item/%E4%B8%89%E9%97%A8%E9%97%AE%E9%A2%98/1242689?fr=aladdin
其次根据题目需求,代码实现,这里用的是java
1 public static void main(String[] args) { 2 Random r = new Random(); 3 4 int no=0; 5 int yes = 0; 6 int doors = 3; 7 int playCount =1000000; 8 for(int i=0;i<playCount;i++){ 9 //定义三个门 10 ArrayList<Integer> nums = new ArrayList<>(); 11 for(int j=1;j<=doors;j++){ 12 nums.add(j); 13 } 14 15 //rightNum门后是汽车 16 int rightNum = r.nextInt(doors)+1; 17 18 //参赛者第一次选择的是firstNum门 19 int firstNum = r.nextInt(doors)+1; 20 21 //主持人去掉一扇后面是山羊的门 22 int cutNum = r.nextInt(doors)+1; 23 while(cutNum == rightNum || cutNum ==firstNum){ 24 cutNum = r.nextInt(doors)+1; 25 } 26 27 //去掉主持人选中的门 28 for (int j = 0; j < nums.size(); j++) { 29 if(nums.get(j)==cutNum){ 30 nums.remove(j); 31 } 32 } 33 34 //参赛者第二次选择一扇门 35 int secondNum = r.nextInt(doors)+1; 36 while(secondNum == cutNum || secondNum ==firstNum){ 37 secondNum = r.nextInt(doors)+1; 38 } 39 40 //参赛者第二次选择,如果不换门选中汽车,则no加一 41 if(firstNum == rightNum){ 42 no++; 43 } 44 45 46 //参赛者第二次选择,如果换门选中汽车,则yes加一 47 if(secondNum==rightNum){ 48 yes++; 49 } 50 51 } 52 //循环实验,输出结果 53 System.out.println("no:"+no+"\tyes:"+yes+"\ttotal:"+(no+yes)+"\tplayCount:"+playCount); 54 55 }
结果是换门有更大的概率获得汽车,但门的数量越多,换与不换的概率越相近
时间: 2024-10-08 06:57:47