Currently, I am taking a course in computer science, which is technically for beginners, but I feel that all the tasks they give me are more difficult than I can handle.
This quest requires me to simulate a coin. Three players play the game, and each of them has special requirements for victory:
- One wins if there are 2 heads of results and the total number of throws even
- One wins if there are 2 results, and the total number of views is
- One wins if there are 2 results: tails or heads, and the total number of throws is odd
What I have to do is run the experiment 300 times. Each time I have to determine which of the three won and how many times. And I'm really stuck. I have almost no code, but I have a very general idea of what the code should be, but I can’t put it in Java.
For my appointment, I need to display the binary sequence that made the person win.
My idea:
- Initialize a counter (1, 2, 3) for each person so that I can track how many times they win.
- Initialize head count and tail counts to track randomly generated sequences.
- for . , , 300 , if, , . if , . System.out.println(); .
- ,
EDIT:
, , , ! , , , . , ; 300 , , . , , , reset . , . - ?
EDIT:
. , 300 ! . ; 1 , , , 2 . , , 1 , . - if?
import java.util.Random;
public class Assignment3e
{
public static void main(String[] args)
{
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
Random coin = new Random();
for(int i = 0; i <= 300; i++){
int headCount = 0;
int tailsCount = 0;
for(int coinToss = 0; coinToss <= 3; coinToss++){
int random = (int) (Math.random() * 6) + 1;
String binary = Integer.toBinaryString(random);
boolean result = coin.nextBoolean();
if(result){
headCount++;
}
else{
tailsCount++;
}
if(headCount == 2 && binary.length() % 2 ==0){
counter1 = counter1 + 1;
System.out.println(binary + " Amy wins.");
}
else if(tailsCount == 2 && binary.length() % 2 == 0){
counter2 = counter2 + 1;
System.out.println(binary + " Penny wins.");
}
else if(headCount == 2 || tailsCount == 2 && binary.length() % 2 != 0){
counter3 = counter3 + 1;
System.out.println(binary + " Bernie wins.");
}
}
}
System.out.println("Amy wins " + counter1 + " times.");
System.out.println("Penny wins " + counter2 + " times.");
System.out.println("Bernie wins " + counter3 + " times.");
}
}