INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of MonteHall.java.

/*************************************************************************
 *  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 10000000
 * Fraction of games won = 0.666586
 *
 *
 *  Note:  true winning probability = 2/3.
 *
 *************************************************************************/

public class MonteHall {

   public static void main(String[] args) { 
      int N = Integer.parseInt(args[0]);
      int prize;                          // where the prize is hidden
      int choice;                         // contestant's first choice
      int reveal;                         // door that Monte Hall reveals
      int other;                          // remaining door
      int wins = 0;                       // # times you win by switching
      double r;                           // random number between 0 and 1

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

         // host hides prize behind 1 of 3 doors
         r = Math.random();
         if      (r < 1.0 / 3.0) prize = 1;
         else if (r < 2.0 / 3.0) prize = 2;
         else                    prize = 3;

         // contestant selects 1 of 3 doors
         r = Math.random();
         if      (r < 1.0 / 3.0) choice = 1;
         else if (r < 2.0 / 3.0) choice = 2;
         else                    choice = 3;

         // host reveals a door not containing prize at random
         reveal = 0;
         do {
            r = Math.random();
            if      ((r < 1.0 / 3.0) && (choice != 1) && (prize != 1)) reveal = 1;
            else if ((r < 2.0 / 3.0) && (choice != 2) && (prize != 2)) reveal = 2;
            else if (                   (choice != 3) && (prize != 3)) reveal = 3;
         } while (reveal == 0);

         // hack to compute the remaining door which contestent switches to
         other = 1 + 2 + 3 - reveal - choice;

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

      // cast needed to avoid integer division
      System.out.println("Fraction of games won = " + 1.0 * wins / N);
   }

}


Last updated: Wed Feb 11 18:07:23 EST 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.