Search code examples
rwhile-loopdice

Number of Dice rolling till reaches a Stop Value


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.


Solution

  • 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