# Generating Random Numbers Until a Condition is Met

I am trying to write the following loop:

• Step 1:Generate a random number from 1:6 until "5" is obtained (else restart Step 1)
• Step 2:If the first "5" is obtained, generate another random number - if this other random number is "4" then finish, else restart from Step 1
• Count the total number of tries it took you to from the first time you started Step 1 all the way until the first time you finished Step 2

Here is my attempt:

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

mean(replicate(roll_pair_dice(), 10000))
``````

I am not sure if this is correct. Our prof told us that to get 4 followed 6 should take 36 tries on average - and a 6 followed by a 6 should take 42 tries on average.

It looks like you're not incrementing roll_count after getting roll1.

1 Like

Thank you for pointing this out! Can you please show me how I should implement this if you have time?

Thank you so much!

After
`roll1 <- sample(1:6, 1)`
`roll_count <- roll_count + 1`