Search code examples
rprobabilitydice

Dice Probability in R script


Roll five six-sided dice. Write a script in R to calculate the probability of getting between 15 and 20 as the total sum of your roll. Exact solutions are preferred.

dice <- expand.grid(1:6, 1:6, 1:6, 1:6, 1:6)
dice.sums <- rowSums(dice)
mean(15 <= dice.sums & dice.sums <=20)
[1] 0.5570988



This is the code that I have, which the answer happens to be 0.5570988. Is there any other way to write it in one line of code? Or condense it? Any thoughts are welcome.


Solution

  • From this answer, which references this answer:

    dDice <- Vectorize(function(k, m, n) {
      # returns the probability of n m-sided dice summing to k
      s <- 0:(floor((k - n)/m))
      return(sum((-1)^(s)*choose(n, s)*choose(k - s*m - 1, n - 1))/m^n)
    }, "k")
    
    sum(dDice(15:20, 6, 5))
    #> [1] 0.5570988
    

    Note that I did not take care in the order in which I added the terms of the alternating sum, so the function may need to be modified to return accurate probabilities for larger input values.