Search code examples
javadice

Most likely sum of two dices


I have two dices where the user can chooses the amount of faces on. I want to write a code to output the most likely outcome. For example if the user chooses 2 6-sided dices, then the outcome should be 7. But if the user chooses one 3-sided and one 4-sided dice, the output should be 4 and 5. I have seen examples where you calculate how likely each different sum is in different loops, but I am wondering if there is an easier way to go since I only care about the MOST likely sum, and not all sums.

Any advice or help would be appreciated!

Edit. Since it has not been appreciated to print all different attempts that I have done since there has been complaints about unnecessary code to read, I will link you to different examples I have tried, but then deleted since they seemed to be unnecessarily long for my problem. https://coderanch.com/t/517923/java/Dice-probability-program-nested-loops I realized that that example wasn't fitted since that required an amount of rolls that I will not determine. I then tried to simply try all different possible combinations by using a while loop but I got stuck in the middle and therefore chose not go with it.

Now I only have:

Scanner scanner = new Scanner (System.in);
while (scanner.hasNextInt()) {
int x,y;
x=scanner.nextInt();
y=scanner.nextInt();
if (x==y) {
int z = x+1; 
System.out.println(z)
} else {
int z= ((x+y)/2)+1;
System.out.println(z);
}
}

Problem: if there are two different numbers of faces, the variable z only prints out ONE of the sum that are equally as likely to occur.


Solution

  • Let a and b be the number of sides and assume a is less than (or equal to) b. Then all sums between a+1 and b+1 and have the same likelihood (of a/(a+b)) and that likelihood is also maximal. How you want to return this in your code is up to you.