Search code examples
rloopssimulationprobability

Simulation in R for probability puzzle


Let two integers such that 1<a<7 and 2<b<5.We play the following game: We start with a euros and we roll a dice.If the result of the dice is at least b we earn 1 euro and we lose 1 euro otherwise. The game ends if we reach 8 euros (winners) or in 0 (losers). We prefer to be ?

A) Rich: we start with a equals 6 euros , but unlucky because b equals 5. B) Mediocre: we start with a equals 4 and b equals 4 C) Lucky: we start with a equals 2 but b equals 3.

How can I do it in R using simulation in order to decide If I want to be rich ,mediocre or lucky?

My effort


gamble <- function(a,n,p) {
  stake <- a
  while (stake > 0 & stake < n) {
    bet <- sample(c(-1,1),1,prob=c(1-p,p))
    stake <- stake + bet
  }
  if (stake == 0) return(1) else return(0)
}   

a <- 6
n <- 8
p <- 1/3
trials <- 100000
simlist <- replicate(trials, gamble(a, n, p))
mean(simlist) # Estimate of probability that gambler is ruined

a <- 4
n <- 8
p <- 1/2
trials <- 100000
simlist <- replicate(trials, gamble(a, n, p))
mean(simlist) 


a <- 2
n <- 8
p <- 2/3
trials <- 100000
simlist <- replicate(trials, gamble(a, n, p))
mean(simlist) 



Solution

  • We could define a function f() that uses recursion.

    f <- \(a, b) {
      s <- sample(6, 1)
      l <- length(a)
      a <- c(a, a[l] + ifelse(s >= b, 1, -1))
      if (a[l + 1] %in% c(0, 8)) return(a)
      else return(f(a, b))
    }
    
    R <- 1e5
    set.seed(42)
    r0 <- replicate(R, Map(f, c(6, 4, 2), c(5, 4, 3)))
    rowMeans(matrix(rapply(r0, \(x) x[length(x)] == 8), 3))
    # [1] 0.24668 0.49885 0.75435