Chapter 12 Gambler’s Ruin

8 Write a computer program which simulates the game in Exercise 6 for the case p = q = 1/2, and M = 10.

For context 6: In the text, it was shown that if q < p, there is a positive probability that a gambler, starting with a stake of 0 dollars, will never return to the origin. Thus, we will now assume that q ≥ p. Using Exercise 5, show that if a gambler starts with a stake of 0 dollars, then the expected number of times her stake equals M before returning to 0 equals (p/q)M, if q > p and 1, if q = p….

# define the variables
M <- 10 #the expected number of times her stake equals M before returning to 0
p <- .5 #p of winnning
q <- .5 #p of losing
n_simulations <- 10000  # simulations

# simulate game
simulate_game <- function(p, q, M) {
  stake <- 0
  reached_M <- 0
  
# loop (using while) until the stake reaches M or -M
  while (stake < M && stake > -M) {
    
# Simulate a coin toss,
    outcome <- sample(c(-1, 1), size = 1, prob = c(q, p))
    
 # Update the stake based on the outcome of the coin toss, if stake is 0 then it goes to 1 for win, -1 for loss
    if (outcome == 1) {
      stake <- stake + 1
    } else {
      stake <- stake - 1
    }
    
# Check if the stake equals M and increment the counter
    if (stake == M) {
      reached_M <- reached_M + 1
    }
  }
  
  return(reached_M)
}

# Simulate games and calculate the average number of times the stake equals M before returning to 0
reached_M <- replicate(n_simulations, simulate_game(p, q, M))
average_num_reached_M <- mean(reached_M)