问题描述: 1970年互动游戏节目Let's Make a Deal中,参与者面前有三道门,其中一道门后面藏有奖品。参与者首先选择一道门,主持人从另外两道门中选择打开其中一道门(后面没有奖品的门)。参与者获得一次更改选择的机会,重新选择剩下的那道门,问题是参与者是否应该改变选择,从而能够有更大的机会获得奖品。直观上,参与者最初选择的门和剩下的门具有相同的概率可能藏有奖品,所以没必要改变选择。请编写程序MonteHall模拟该游戏,测试直观上是否正确。
- /*************************************************************************
-
* Compilation: javac MonteHall.java
-
* Execution: java MonteHall N
-
*
-
* Plays the Monte Hall game N times with the switching strategy
-
* and reports the fraction of games won.
-
*
-
* Sample execution:
-
*
-
* % java MonteHall 1000
-
* Fraction of games won = 0.66
-
*
-
* Note: true winning probability = 2/3.
-
*
-
*************************************************************************/
-
public class MonteHall {
-
public static void main(String[] args) {
-
int N = Integer.parseInt(args[0]); // trials
-
int wins = 0; // times you win by switching
-
-
// repeat experiment N times
-
for (int i = 0; i < N; i++) {
-
-
//host hides prize behind 1 of 3 doors uniformly at random
-
int prize = 1 + (int)(3 * Math.random());
-
// contestant select 1 of 3 doors uniformly at random
-
int choice = 1 + (int)(3* Math.random());
-
-
//at random, host reveals an unchosen door not coitaining prize
-
int reveal;
-
do {
-
reveal = 1 + (int)(3*Math.random());
-
} while((reveal == choice) || (reveal == prize));
-
-
//hack to compute the remaining door which contestent swithces to
-
-
int other = 1 + 2 + 3 - reveal - choice;
-
-
//switching leads to a win
-
if (other == prize) wins++;
-
}
-
-
//avoid integer division
-
System.out.println("Fraction of games won = " + 1.0 * wins / N);
-
}
-
}
阅读(458) | 评论(0) | 转发(0) |