I am trying to write the R code for a game with the following rules:
A coin is flipped for 15 turns with a starting score of 0
Each turn there is a 0.7 probability of heads and a 0.3 probability of tails
When heads, the score is score = score +3 and when tails the score = score -1
While my code runs, I am not sure if its doing what the rules of the game are saying.
library(dplyr)
generate_all_paths <- function(num_turns, m, n, p1, p2) {
if (num_turns == 0) {
return(list(c()))
} else {
paths_plus <- generate_all_paths(num_turns - 1, m, n, p1, p2)
paths_minus <- generate_all_paths(num_turns - 1, m, n, p1, p2)
paths_plus <- lapply(paths_plus, c, m)
paths_minus <- lapply(paths_minus, c, n)
return(c(paths_plus, paths_minus))
}
}
initial_score <- 0
m <- 3
n <- -1
p1 <- 0.7
p2 <- 0.3
paths <- generate_all_paths(15, m, n, p1, p2)
df <- do.call(rbind, lapply(paths, function(x) { c(initial_score, x, rep(NA, max(lengths(paths)) - length(x))) }))
df <- as.data.frame(df, stringsAsFactors = FALSE)
df$final_score <- rowSums(df, na.rm = TRUE)
df <- df %>%
group_by(final_score) %>%
summarise(count = n()) %>%
mutate(probability = count / sum(count))
df
Is my code correct?
Thanks!