To answer this question, I’ll write a function called raquetball that simulates a single game, based on the probabilities given.
raquetball <- function() {
#tracks who the current server is so we know who to give a point to
who_is_serving <- 1
#probabilities
my_win_prob_while_serving <- 0.6
my_win_prob_opponent_serving <- 0.5
#1 = I win, 0 = You win
outcomes <- c(1,0)
#tracking points
my_points <- 0
her_points <- 0
#game continues (loops) until someone reaches 21 points
while (my_points < 21 & her_points < 21) {
#if opponent is serving, use 0.5 probability
if (who_is_serving == 0) {
probabilities <- c(my_win_prob_opponent_serving, 1- my_win_prob_opponent_serving)
who_won <- sample(outcomes, 1, prob = probabilities)
#If my opponent wins, she gets a point, otherwise I become the server
if (who_won == 0) {
her_points <- her_points + 1
} else {
who_is_serving <- 1
}
} else {
#if I'm serving, I use 0.6
probabilities <- c(my_win_prob_while_serving, 1- my_win_prob_while_serving)
who_won <- sample(outcomes, 1, prob = probabilities)
#If I win, I add a point to my total, otherwise the other player serves
if (who_won == 1) {
my_points <- my_points + 1
} else {
who_is_serving <- 0
}
}
}
if (my_points == 21) {
return(1)
}
else {
return(0)
}
}
Now, i’ll use a for loop to simulate the game 10,000 times and see how many times I win out of those 10,000 to determine the probability.
count <- c()
simulation_runs <- 10000
for (i in seq(simulation_runs)) {
game <- raquetball()
count <- c(count, game)
}
probability_to_win <- sum(count) / length(count)