RW = function (k, N, p = 0.5) { pos <- k rw <- pos status <- 0 if (pos == N) status <- "win" if (pos == 0) status <- "ruin" while (status == 0) { x <- rbinom(1, 1, p) if (x == 1) pos <- pos + 1 if (x == 0) pos <- pos - 1 rw <- c(rw, pos) if (pos == N) status <- "win" if (pos == 0) status <- "ruin" } l <- list(rw = rw, result = status) return(l) } simRW = function(num, k, N, p) { q = 1 - p count = 0 count1 = 0 exp.length = rep(0, num) for(i in 1:num) { a = RW(k, N, p) exp.length[i] = (length(a$rw) - 1) if(a$result == "ruin") { count = count + 1 if(a$rw[2] == (k-1)) count1 = count1 + 1 } if(i == 1) { plot(1:length(a$rw) - 1, a$rw, xlim = c(0, 2 *length(a$rw)), ylim = c(0, N), typ = "l", lwd = 3, xlab = "Number of Games", ylab = "Money (£)", main = paste("Gambler's Ruin Simulation : p = ", round(p, 2), ", k = ",round(k, 0), ", N = ", round(N, 0), sep = "")) } else { lines( 1:length(a$rw) - 1, a$rw, col = i, lwd = 3) } } cat(paste("Proportion absorbed at 0 = ", round(count/num,3), "\n", sep = "")) cat(paste("Proportion of walks absorbed at 0 for which 1st move was down = ", round(count1/count,3), "\n", sep = "")) cat(paste("Average game length (until absorption at 0 or N) = ", mean(exp.length), "\n", sep = "")) }