simultation in R - stochastic problem

28 Views Asked by At

Two teams play a series of games, the chance of winning is 0.5 independently. The winning team is the one that comes first to four wins in a row. How do I calculate the expectation of the number of games in a series using simulation?

I need to create simultation of choise between A,B. one time group A wins and other tome group B. the first group who got 4 wins in a row, she is the winner and we stop the game.

I stated like this - (don't judge me I started ussing R just in the last week)

    # 2 Teams play each other, each Team has a chance to win p = 0.5
# Only the Team wining in a row of 4 strikes wins 
# How many times need to be played till the chance is very high that this will happen

#how many games 
c_nb_of_games <- 1e2L

#how many times to simulate
c_index = 1:100

for(j in 1:length(c_index)){
  #Create a vecor that a team wins by chance of 0.5,  => 1 = win game, 0 = lose game
  c_wins <- rbinom(c_nb_of_games, 1, 0.5)
  
  #check for the index (number of games till one team wins 4 times in a raw)
  for(i in 4:length(c_wins)){
    if(sum(c_wins[seq(i-3,i,1)]) == 4){
      #print(i)
      c_index[j] <- i
      break
    }
  }
}
hist(c_index)

I know it's not a good code, but I dont know how to create a "if" to stop if one group get to 4 wins in a row.. help?