Coin Flipping Game in R

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!

If you save the definition of generate_all_paths() in its own file, say, generate_all_paths.r, then you can place a break point on the first line (if (num_turns == 0) {...) by clicking to left of the corresponding line number in the editor.

Then, you could run debug(generate_all_paths), and the next time you run generate_all_paths(), you'll enter debug mode, where you can walk through the code step by step and inspect values of paths_plus and path_minus as they change. I would start by running generate_all_paths() with small values for num_turns, m, and n.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.