
// introductory program to demonstrate Monte Carlo simulation under Java

// simulates the tossing of a coin 10 times, calculating various
// probabilistic quantities:

//    P(6 heads)
//    P(2 heads in the first 4 tosses | 6 heads total)
//    E(square of the total number of heads)

public class Coin  {

   static final int NREPS = 100000;  // number of times the 10-toss
                                    // experiment is to be repeated 

   public static void main(String[] Args) 

   {  int N6 = 0,  // # of repetitions in which there are 6 heads
          N246 = 0,  // # of reps in which the 1st 4 tosses yield 2 heads,
                     // among reps in which there are 6 heads total
          SumH2 = 0,  // sum of the squares of heads counts
          Heads,Outcome,Rep;
      boolean Event24;

      for (Rep=0; Rep < NREPS; Rep++)  {
         Heads = 0;
         Event24 = false;
         for (int Toss=0; Toss < 10; Toss++)  {
            Outcome = (int) (2 * Rnd());
            if (Outcome == 1)  {  // heads
               Heads++;
            }
            if (Toss == 3 && Heads == 2) Event24 = true;
         }
         if (Heads == 6)  {
            N6++;
            if (Event24) N246++;
         }
         SumH2 += Heads*Heads;
      }

      System.out.println("P(6 heads) = "+(float) N6/NREPS);
      System.out.println("P(2 of 1st 4 | 6 heads) = "+(float) N246/N6);
      System.out.println("E(heads squared) = "+(float) SumH2/NREPS);
   }

   // U(0,1) random variable generator
   static float Rnd()
 
   {  return (float) Math.random(); }

}


