In a coin flip game, you flip a fair coin until the difference between the number of heads and number of tails is 3. You are paid $8 at the end, but you have to pay $1 for each flip of the coins. Use N =100000 simulations and find the expected amount you could win.
I was able to use the following code for 1 game but it breaks for N=100,000 as it is too long. How can I turn this into a function that will give me expected payoff for 100,000 games?
#For 1 game
# number of games to play
n_games <- 1
bias <- 0.5
game_payoff <- c()
for (i in seq_len(n_games)) {
cost <- 0
flip_record <- c()
payoff <- c()
repeat{
cost <- cost + 1
flip <- rbinom(1, 1, prob = bias)
flip_record <- c(flip_record, flip)
# number of 0s/tails
n_tails <- length(flip_record) - sum(flip_record)
# number of 1s/heads
n_heads <- sum(flip_record)
if (abs(n_tails - n_heads) == 3) {
# record game payoff
game_payoff <- c(game_payoff, 8 - cost)
# print game payoff
print(paste0("single game payoff: ", 8 - cost))
break
}
}
}
Here is a solution.
I have added an argument
bankruptcyin order to avoid very long games.In the example run below, only 10,000 games (
n_games) are played.Created on 2022-10-06 with reprex v2.0.2