play_volley <- function(you_serve) { if (you_serve) { # If you are serving, calculate if you win the volley with probability 0.6 win_volley <- runif(1) < 0.6 } else { # If your opponent is serving, calculate if you win the volley with probability 0.5 win_volley <- runif(1) < 0.5 } return(win_volley) }
play_game <- function() { # Initialize scores your_score <- 0 opponent_score <- 0 # Loop until either you or your opponent reaches 21 points
while (your_score < 21 && opponent_score < 21) { # Play a volley with you serving if (play_volley(TRUE)) { # If you win the volley while serving, increase your score your_score <- your_score + 1 } else { # If you lose the volley while serving, your opponent gets the serve # Play a volley with your opponent serving if (play_volley(FALSE)) { # If you win the volley while your opponent serves, increase your score your_score <- your_score + 1 } else { # If you lose the volley while your opponent serves, increase your opponent’s score opponent_score <- opponent_score + 1 } } } # Return TRUE if you win the game, FALSE otherwise return(your_score >= 21) }
estimate_win_probability <- function(num_simulations) { # Initialize count of games won games_won <- 0 # Simulate multiple games for (i in 1:num_simulations) { # Play a game and increment count if you win if (play_game()) { games_won <- games_won + 1 } } # Calculate and return the estimated win probability return(games_won / num_simulations) }
num_simulations <- 500000
results <- numeric(num_simulations)
for (i in 1:num_simulations) { results[i] <- estimate_win_probability(1) }
win_probability <- mean(results)
cat(“Estimated probability of winning a game:”, win_probability, “”)
#At 10K simulations, the probability of my victory was 1. #At 100K simulations, the probability of my victory was 0.99999. #At 500K simulations, the probability of my victory was 0.999994. #It means that I am almost always certain to win.