Advertisement
Guest User

FlipCoin.java

a guest
Apr 17th, 2010
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class FlipCoin
  4. {
  5.     public static void main(String[] args)
  6.     {
  7.         // Set up basic variables for use in the program.
  8.         String a = "THH", b = "THT", flips;
  9.         Random rand = new Random();
  10.         double aAverage = 0, bAverage = 0;
  11.         int count;
  12.  
  13.         // Run the program 10000 times to get a good sample size.
  14.         for (count = 0; count < 10000; count++)
  15.         {
  16.             // Initialise flips with 3 (minimum amount for pattern).
  17.             flips = "";
  18.             for (int i = 0; i < 3; i++)
  19.             {
  20.                 // If true, the coin lands heads up (H). If false, tails up (T).
  21.                 if (rand.nextBoolean())
  22.                 {
  23.                     flips += "H";
  24.                 }
  25.                 else
  26.                 {
  27.                     flips += "T";
  28.                 }
  29.             }
  30.  
  31.             // Keep adding coin flips until both patterns are found.
  32.             while (flips.indexOf(a) == -1 || flips.indexOf(b) == -1)
  33.             {
  34.                 // If true, the coin lands heads up (H). If false, tails up (T).
  35.                 if (rand.nextBoolean())
  36.                 {
  37.                     flips += "H";
  38.                 }
  39.                 else
  40.                 {
  41.                     flips += "T";
  42.                 }
  43.             }
  44.  
  45.             /*
  46.              * Total up the number of flips needed until each pattern is found.
  47.              * Since the indexOf() method returns the index of the first
  48.              * character, we need to add the length of the pattern to get the
  49.              * actual number of flips. So if the pattern is 3 characters long,
  50.              * and is found at the first index (0) it must have been found in
  51.              * 3 tosses (0, 1, 2).
  52.              */
  53.             aAverage += flips.indexOf(a) + a.length();
  54.             bAverage += flips.indexOf(b) + b.length();
  55.         }
  56.        
  57.         // Compute the averages by dividing the totals by the iteration count.
  58.         aAverage /= count;
  59.         bAverage /= count;
  60.  
  61.         // Print out the results.
  62.         System.out.println(a + " found after an average of " + aAverage +
  63.             " (~" + Math.round(aAverage) + ") flips.");
  64.         System.out.println(b + " found after an average of " + bAverage +
  65.             " (~" + Math.round(bAverage) + ") flips.");
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement