What is the probability of rolling at least $n$ consecutive numbers when rolling $k$ dice?

114 Views Asked by At

I am trying to code a game that turned out to be more complicated than expected. The complication comes down to a function that attempts to calculate the chance of at least $n$ consecutive numbers out of a total of $k$ dice rolled. The function only has to work for integer values of $n$ and $k$, and $2\le n\le k\le 6$. I am looking for a formula I can use to calculate all possibilities and store them as variables, or a javaScript function that can take parameters $n$ and $k$ and then do the calculation that way. I have been trying for a while now and cannot find a way to correctly calculate these probabilities to match experimental results. I have tried a lot of different javaScript function ideas to iterate and calculate these odds, but none of my attempts works for both $n=k=2$ and $n=3, k=6$. Example combinations that work for $n=3$ and $k=6$ are $1, 2, 3, 6, 6, 6; \; 3, 5, 2, 1, 4, 6$ and 1, 2, 3, 4, 6. Thanks for any help.

1

There are 1 best solutions below

2
On

There are only $6^6 \approx 50,000$ possible sequences of 6 rolls. Just enumerate all of them, and count how many meet your requirements. A program to do that should finish in milliseconds.

Or, precompute the answer for each $k,n$ satisfying $2 \le n \le k \le 6$. There are only 15 pairs of values $(n,k)$, so you can precompute the answer for each pair, and hardcode all of those in your code as a lookup table, and just look up the desired entry at runtime.