Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222291
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Java

2011-08-30 09:41:04

问题描述: 1970年互动游戏节目Let's Make a Deal中,参与者面前有三道门,其中一道门后面藏有奖品。参与者首先选择一道门,主持人从另外两道门中选择打开其中一道门(后面没有奖品的门)。参与者获得一次更改选择的机会,重新选择剩下的那道门,问题是参与者是否应该改变选择,从而能够有更大的机会获得奖品。直观上,参与者最初选择的门和剩下的门具有相同的概率可能藏有奖品,所以没必要改变选择。请编写程序MonteHall模拟该游戏,测试直观上是否正确。

  1. /*************************************************************************
  2.  * Compilation: javac MonteHall.java
  3.  * Execution: java MonteHall N
  4.  *
  5.  * Plays the Monte Hall game N times with the switching strategy
  6.  * and reports the fraction of games won.
  7.  *
  8.  * Sample execution:
  9.  *
  10.  * % java MonteHall 1000
  11.  * Fraction of games won = 0.66
  12.  *
  13.  * Note: true winning probability = 2/3.
  14.  *
  15.  *************************************************************************/
  16. public class MonteHall {
  17.     public static void main(String[] args) {
  18.  int N = Integer.parseInt(args[0]); // trials
  19.  int wins = 0;  // times you win by switching

  20.  // repeat experiment N times
  21.  for (int i = 0; i < N; i++) {

  22.      //host hides prize behind 1 of 3 doors uniformly at random
  23.      int prize = 1 + (int)(3 * Math.random());
  24.     // contestant select 1 of 3 doors uniformly at random
  25.      int choice = 1 + (int)(3* Math.random());

  26.      //at random, host reveals an unchosen door not coitaining prize
  27.      int reveal;
  28.      do {
  29.          reveal = 1 + (int)(3*Math.random());
  30.      } while((reveal == choice) || (reveal == prize));

  31.      //hack to compute the remaining door which contestent swithces to

  32.      int other = 1 + 2 + 3 - reveal - choice;

  33.      //switching leads to a win
  34.      if (other == prize) wins++;
  35.  }

  36.      //avoid integer division
  37.      System.out.println("Fraction of games won = " + 1.0 * wins / N);
  38.     }
  39.    }


阅读(461) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~