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;
}
}
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With