Reputation: 1
I'm a beginner to R and I wanted to simulate a coin toss of three coins until only one coin has a different outcome than the two. Then I want to try this test 10000 times. However, when I run my code, the loading icon runs indefinitely after I get this output:
This is my code:
aWins <- 0
bWins <- 0
cWins <- 0
totalWins <- 0
a <- 0
b <- 0
c <- 0
while(totalWins < 10000){
while(a == b && b == c){
a <- sample(0:1, 1)
b <- sample(0:1, 1)
c <- sample(0:1, 1)
print("OOF")
if(a != b && b == c){
aWins <- aWins + 1
}
if(b != a && a == c){
bWins <- bWins + 1
}
if(c != b && b == a){
cWins <- cWins + 1
}
print(totalWins)
totalWins <- aWins + bWins + cWins
}
}
print("A wins: " + aWins)
print("B wins: " + bWins)
print("C wins: " + cWins)
print("Total wins: " + totalWins)
Upvotes: 0
Views: 212
Reputation: 74605
I think your looping logic is broken
Problem: You keep looping until the number of wins exceeds 10000 but this doesn't represent 10000 games because games where all coins are equal don't count, so you'll have to flip many more than 10k to reach a win.
Solution: I think your if if if should actually be if elseif elseif else, with the else being "nobody won" and a counter tracks that so that total wins is a + b + c + nobody.
Edit: I thought from the title of the question you wanted to do 10k flips, but then reread the body and it seems a game is "flip until one is different", in which case this counting logic is OK
Problem: You only actually flip your coins if they're all heads or all tails (second while loop) - as soon as one coin flips different to the others (the only way the game can win for that coin) the inner loop will stop running, no more flips will occur, you'll never reach 10k.
Solution: Get rid of this inner while loop and put the code in it in the outer loop instead, OR reset your values of a b and c to be the same between the two while statements so the inner loop has a chance to run again when the outcome of the flip is win for one of the coins
Upvotes: 1