Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class FlipCoin
- {
- public static void main(String[] args)
- {
- // Set up basic variables for use in the program.
- String a = "THH", b = "THT", flips;
- Random rand = new Random();
- double aAverage = 0, bAverage = 0;
- int count;
- // Run the program 10000 times to get a good sample size.
- for (count = 0; count < 10000; count++)
- {
- // Initialise flips with 3 (minimum amount for pattern).
- flips = "";
- for (int i = 0; i < 3; i++)
- {
- // If true, the coin lands heads up (H). If false, tails up (T).
- if (rand.nextBoolean())
- {
- flips += "H";
- }
- else
- {
- flips += "T";
- }
- }
- // Keep adding coin flips until both patterns are found.
- while (flips.indexOf(a) == -1 || flips.indexOf(b) == -1)
- {
- // If true, the coin lands heads up (H). If false, tails up (T).
- if (rand.nextBoolean())
- {
- flips += "H";
- }
- else
- {
- flips += "T";
- }
- }
- /*
- * Total up the number of flips needed until each pattern is found.
- * Since the indexOf() method returns the index of the first
- * character, we need to add the length of the pattern to get the
- * actual number of flips. So if the pattern is 3 characters long,
- * and is found at the first index (0) it must have been found in
- * 3 tosses (0, 1, 2).
- */
- aAverage += flips.indexOf(a) + a.length();
- bAverage += flips.indexOf(b) + b.length();
- }
- // Compute the averages by dividing the totals by the iteration count.
- aAverage /= count;
- bAverage /= count;
- // Print out the results.
- System.out.println(a + " found after an average of " + aAverage +
- " (~" + Math.round(aAverage) + ") flips.");
- System.out.println(b + " found after an average of " + bAverage +
- " (~" + Math.round(bAverage) + ") flips.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement