利用程序解决三扇门问题(java)

来源:互联网 发布:matebook x ubuntu 编辑:程序博客网 时间:2024/06/05 09:17

三门问题(Monty Hall problem)亦称为蒙提霍尔问题、蒙特霍问题或蒙提霍尔悖论,大致出自美国的电视游戏节目Let’s Make a Deal。问题名字来自该节目的主持人蒙提·霍尔(Monty Hall)。参赛者会看见三扇关闭了的门,其中一扇的后面有一辆汽车,选中后面有车的那扇门可赢得该汽车,另外两扇门后面则各藏有一只山羊。当参赛者选定了一扇门,但未去开启它的时候,节目主持人开启剩下两扇门的其中一扇,露出其中一只山羊。主持人其后会问参赛者要不要换另一扇仍然关上的门。问题是:换另一扇门会否增加参赛者赢得汽车的机率?如果严格按照上述的条件,即主持人清楚地知道,哪扇门后是羊,那么答案是会。不换门的话,赢得汽车的几率是1/3。换门的话,赢得汽车的几率是2/3。
这个问题亦被叫做蒙提霍尔悖论:虽然该问题的答案在逻辑上并不自相矛盾,但十分违反直觉。这问题曾引起一阵热烈的讨论。

import java.util.*;/** * Created by chenmeiji on 16/10/12. */public class justForTest {    public static void main(String[] args) {       //规则,当生成随机数1,则选择第一扇门,2选择第二扇门,3选择第三扇门        //同样当生成1,2,3分别代表第一,第二,第三扇门有大奖        //当猜中时候wintimes++,否则losttimes++        int winTimes=0;        int lostTimes=0;        int rightDoorNum=0;        int firstChance=0; //下表0,1,2分别代表1,2,3扇门,当值为1的时候锁门        int opendoor=0;        int chance=0;        int scendChance=0;        Random random=new Random();        //统计概率        Scanner scanner=new Scanner(System.in);        //chance=1坚持选择,否重新作出选择        System.out.println("如果你坚持之前的选择请输入1,否则请输入0");        chance=scanner.nextInt();        //开始游戏        for(int i=0;i<10000;i++){            //生成正确的门        rightDoorNum=random.nextInt(3)+1;            //挑战者作出选择            firstChance=random.nextInt(3)+1;            //主持人开启一扇错误的门,该门不能与挑战者选择的门相同            while (true){                opendoor=random.nextInt(3)+1;                if(opendoor!=firstChance){                    break;                }            }            //坚持选择            if(chance==1){                if(firstChance==rightDoorNum){                    winTimes++;                }else{                    lostTimes++;                }            }else{                //重新选择                while (true){                    scendChance=random.nextInt(3)+1;                    if(scendChance!=opendoor){                        break;                    }                }                if (scendChance==rightDoorNum){                    winTimes++;                }else {                    lostTimes++;                }            }        }        System.out.println(winTimes);        System.out.println(lostTimes);        if(chance==1){            System.out.println("坚持选择胜利的概率为:"+((double)winTimes/(double)10000));        }else{            System.out.println("重新选择胜利的概率为:"+((double)lostTimes/(double)10000));        }    }}
0 0
原创粉丝点击