Checking to see if a Random amount of Dice are the Same

49 Views Asked by At

The motivation for this question comes from a simple program that I tried to write.

The game is simple. I want to roll some dice. If all the dice are the same, then I win. If they are different, then I can roll again or roll again with a different number of dice.

Say that I have an array of numbers. Each die roll is stored inside the array. The length of this array can vary at the start of each game (number of dice). The problem I had stemmed from checking if all the numbers in the array are the same. I had the "bright" idea of summing the numbers in the array, divide the sum by the length of the array and checking if it is equal to any single element of the array.

For example, Say I roll 3 dice and the numbers are 4, 4, 4. The sum of the array is 12. 12 divided by the length of 3 is 4, which is an element of the array.

However, there is a problem. Say I roll again and the numbers are 5, 3, 4. The requirements for my algorithm are the same but the numbers in the array are not all the same.

This made me wonder, will my algorithm only produce bad results if the array length is an odd integer greater than 1? How can I prove this?

1

There are 1 best solutions below

2
On BEST ANSWER

For an even number of dice it can also fail. Consider $4$ dice rolls with results $3,4,4,5$.

The proof is simple, really. Consider an arrangement of $n$ dice rolls where $n-2$ dice have value $k$, one die has value $k-1$ and another die has value $k+1$.

This works provided $1<k<6$ and $n\geqslant 2$.


In other words, your algorithm checks a condition that is necessary, but not sufficient, for the array to be of equal numbers.