0

This program is supposed to simulate 200 coin flips and print out the length of the longest sequence of heads or tails.

Hey guys, I'm new at programming. I'm stuck in the middle of writing this. Can someone help me to understand the logic behind it? Any help would be appreciated.

public class CoinFlips{

  public static void main(String[] args){

    int headsCount=0;
    int tailsCount=0;
    int countTales=0;
    int countHeads=0;

    for (int i=0 ; i<=200; i++){

      double x= Math.random();
      if (x<0.5){
        countTales++;
      }
      else {
        countHeads++;
      }

        //I'm clueless! 
    }

  }

}
adv12
  • 8,051
  • 2
  • 22
  • 43

2 Answers2

0

Use headsCount and tailsCount to track your max values and reset the counters when the sequence switches from heads to tails like this:

if (x < 0.5) {
   countTales++;
   countHeads = 0; // Reset sequence counter for heads
} else {
   countHeads++;
   countTales = 0; // Reset sequence counter for tails
}

if (countTales > tailsCount) {
   tailsCount = countTales;
}
if (countHeads > headsCount) {
   headsCount = countHeads;
}
Jeff Ward
  • 1,050
  • 6
  • 16
-1

Try this:

public class CoinFlips{

  public static void main(String[] args){

    private int headsCount, tailsCount, countTails, countHeads, maxHeads, maxTails, lastFlip = 0;
    private static final int HEADS = 1;
    private static final int TAILS = 2;

    for (int i=0 ; i<=200; i++){

      double x= Math.random();
      if (x<0.5){
        if (lastFlip == TAILS) {
           tailsCount++;
           if (tailsCount > maxTails) {
              maxTails = tailsCount;
           }
        } else {
          tailsCount = 1;
        }
        lastFlip = TAILS;
        countTails++;
      }
      else {
        if (lastFlip == HEADS) {
           headsCount++;
           if (headsCount > maxHeads) {
              maxHeads = headsCount;
           }
        } else {
          headsCount = 1;
        }
        countHeads++;
      }


    }

    StringBuilder sb = new StringBuilder();
    sb.append("There were ").append(countHeads)
       .append(" heads flipped with the maximum sequential flips of ")
       .append(maxHeads).append(".\n")
       .append("There were ").append(countTails)
       .append(" tails flipped with the maximum sequential flips of ")
       .append(maxTails).append(".\n");
     System.out.print(sb.toString());
  }

}

`

Jimi Kimble
  • 424
  • 4
  • 9