Rewriting the Style of a Function to Match Another Function

I was given this first function over here that rolls dice until a 4 appears followed by a 6 - and counts how many rolls it took:

# original function
roll_from_4_to6 <- function() {
  n <- 1:6
  i <- 1
  previous_4 <- FALSE
  while(TRUE) {
    current_value = sample(n, 1)
    i <- i + 1
    if(previous_4 && current_value == 6) break
    previous_4 <- current_value == 4
  }
  i
}

I then tried to re-write this function based on my own logic of rolling a dice until a 4 appears followed by a 6 - and count how many rolls it took:

# my function
roll_pair_dice <- function() {
    roll1 <- 0
    roll2 <- 0
    roll_count <- 0
    while(!(roll1 == 4 & roll2 == 6)) {
        roll1 <- sample(1:6, 1)
        if(roll1 == 4) {
            roll2 <- sample(1:6, 1)
        }
        roll_count <- roll_count + 1
    }
    return(roll_count)
}

However, I have a feeling that these two functions are not performing the same task - for instance: if I take the average number of rolls from both functions:

> mean(replicate(1000,roll_pair_dice()))
[1] 71.366
> mean(replicate(1000, roll_from_4_to6()))
[1] 36.159

Can someone please show me why my function differs from the original function?

How can I re-write my function so that it accomplishes the same thing as the original function?

Thanks!

In the second one, what is special about rolling a 5 with the first dice ?

1 Like

sorry! It should say "4" ... I made that correction.

Now, should both functions be accomplishing the same thing?

Thank you so much!

Yes, I think you're good with that

This topic was automatically closed 42 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.