Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coin Flip Sequence

Tags:

java

I am stuck with this project. I have to write a coin flip program that generates HTH (121) and I have to count how many tosses would it take to generate that sequence.After that I would need to calculate the average of the sequence.I have the code down below. For example: If I get the output of

1112222222122122122211222121
28
11111122121
11
11121
5

Then my average should be (28+11+5)/3=14.66667. However, i'm stuck coding the average. I have the for loop set up but I'm unsure where or how to put the code for the average.

I was thinking of doing something like

int average= count/N;

but I don't know how to get each count added to each other and where to put this statment witout the compiler saying, "count cannot be resolve to variable"

 package HTX_Program;


public class coinSequence {
        public static int coinFlip() {
            MultiDie coin= new MultiDie(2);
            coin.roll();
            int x = coin.getFaceValue();
            return x;
            }

public static void main(String[] args) {
    final int N=3;
    for(int i=0; i<N; i++){
    String sequenceSoFar = "";
    sequenceSoFar += coinFlip();
    sequenceSoFar += coinFlip();
    sequenceSoFar += coinFlip();
    int count = 3;
    if(!sequenceSoFar.equals("121")) {
        while(!(sequenceSoFar.substring(sequenceSoFar.length() - 3).equals("121"))) {
            sequenceSoFar += coinFlip();
            count++;
        }
    }

    System.out.println(sequenceSoFar);
    System.out.println(count);
    }
    int average= count/N;
}
}
like image 771
Yvette Avatar asked Dec 11 '25 04:12

Yvette


1 Answers

Well first you need to track the total flips across all loops:

int totalFlips = 0;

Then you need to increment this with each flip:

totalFlips++;

Then finally, after the loop, you can calculate the average:

// Note: You have to convert one of the integers to double in order to get correct result.
double average = totalFlips / (double)N;

Here is full modified function:

public static void main(String[] args) {
    final int N=3;
    int totalFlips = 0; // Track total flips.

    for(int i=0; i<N; i++){
        String sequenceSoFar = "";
        sequenceSoFar += coinFlip();
        sequenceSoFar += coinFlip();
        sequenceSoFar += coinFlip();
        int count = 3;
        totalFlips += 3; // add initial 3 flips to total.
        if(!sequenceSoFar.equals("121")) {
            while(!(sequenceSoFar.substring(sequenceSoFar.length() - 3).equals("121"))) {
                sequenceSoFar += coinFlip();
                count++;
                totalFlips++; // increment total flips.
            }
        }

        System.out.println(sequenceSoFar);
        System.out.println(count);
    }

    double average = totalFlips / (double)N; // Calculate average.
}
like image 62
musefan Avatar answered Dec 12 '25 18:12

musefan