3

I am trying to count the number of dice rolls till it reaches to a definite stop value. For example, I want the stop value as 100. I am writing the following code:

sumofsides <- function(stopvalue) {
  totalsum <- 0
  while (totalsum < stopvalue) {
    face <- sample(6, 1, replace= TRUE)
    totalsum <- totalsum + face
  }
  return(total value)
}

sumofsides(100)
[1] 103

When I am writing the following code to get the number of rolling till it reaches to the stop value. But it's always giving value of 1 which is wrong.

numofrolls <- function(stopvalue) {
  totalsum <- 0
  while (totalsum < stopvalue) {
    face <- sample(6, 1, replace= TRUE)
    totalsum <- totalsum + face
  }
  return(length(face))
}

numofrolls(100)
[1] 1

Any help is appreciated.

S Das
  • 3,291
  • 6
  • 26
  • 41
  • Also, you don't need the `replace = TRUE` argument in your call to `sample`. You're performing a brand new call to `sample` every iteration for your loop. – Richard Border Apr 13 '15 at 04:46

1 Answers1

3

In your current loop, you are rewriting totalsum every iteration with a new value, so its length will never go beyond one. One solution would be to use a second variable to count the number of rolls:

rollUntil <- function(n) {
        nRolls   <- 0
        sumRolls <- 0
        while (sumRolls <= n) {
                sumRolls <- sumRolls + sample.int(6, 1)
                nRolls = nRolls + 1
        }
        return(nRolls)
}


# let's look at the distribution of rolls till 100:
hist(replicate(1000,rollUntil(100)))

enter image description here

Richard Border
  • 3,209
  • 16
  • 30