actB4157
actB4157

Reputation: 1

Struggling with simulating N rolls for K dice

The function dice takes a parameter n, representing number of rolls for a single six-sided die. It returns a vector of length n that has elements that are integers b/w 1 and 6. I have created the following code for the dice function below. It seems to run properly when I test it.

dice <- function(n) {
     x <- c(1:6)
     sample(length(x), size = n, replace = TRUE, prob = x)

   }

The function kdice takes two parameters, n and k. The parameter n is denoted for number of rolls done. The number of dice rolled is represented by parameter k. The function should return the sum of the k dices, rolled n times. Somehow I have to implement dice() within this function. Below is what I have completed thus far, however the function returns nothing. I have an If and Else statement to make sure that at least 1 dice was rolled at least 1 time. While loop is to make the sum of NumofDice is outputted until it reaches n. Would appreciate any insights, especially how to incorporate the function Dice() in kdice().

kdice <- function(k, n){
  NumofDice <- sample(1:6, size = k, replace = TRUE)
  RollCount = 0
      if(k>0 && n>0) {
         while(RollCount < n) {
           RollCount = RollCount + 1
           sum(NumofDice)
         }
    }
      else {
        print("No number of dices were rolled")
    }

}

Upvotes: 0

Views: 849

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101753

You can try defining kdice using replicate + colSums like below

kdice <- function(k, n) {
  tryCatch(
    colSums(matrix(replicate(n, dice(k)), nrow = k)),
    error = function(e) print("No number of dices were rolled")
  )
}

which give result like

> kdice(4, 5)
[1] 17 14 22 13 11

> kdice(4, 0)
[1] "No number of dices were rolled"

Upvotes: 0

zimia
zimia

Reputation: 932

kdice <- function(k, n){
  if(k>0 && n>0){
    replicate(n, sum(sample(c(1:6),k, replace=TRUE)))
  }
  else {
    print("No number of dices were rolled")
  }
}

kdice(4,2)
[1] 15  8

Upvotes: 1

Related Questions