For a project, I need to find a way to print every way to roll 5 6 sided dice, order non-important. I have tried using nested for loops like so, but I understand that this is printing permutations instead of combinations:
int counter = 0;
for(int i=1; i<7; i++) {
for(int m = 1; m<7; m++) {
for(int j = 1; j<7; j++) {
for(int k = 1; k<7; k++) {
for(int h = 1; h<5; h++) {
System.out.printf("%2d%2d%2d%2d%2d",i,m,j,k,h);
counter++;
System.out.println(" "+counter);
}
}
}
}
}
Is there an efficient way to do this?
Edit: I should add, this is for java! Thanks!
Edit again: yes, I meant 5 dice that each have 6 sides. Sorry for the confusion
# Answer 1
Consider this reduced example with two six-sided dice:
for (int i = 1; i <= 6; i++)
for (int j = 1; j <= 6; j++)
System.out.println(i + " " + j);
This will output 36 (6^2) combinations. But many are duplicates. For example, the pair of numbers 1 2 and 2 1 are basically the same. What if you could only calculate UNIQUE pairs? Of the 36 listed pairs when running the above code, only 21 are unique combinations. So, how would you do that?
for (int i = 1; i <= 6; i++)
for (int j = i; j <= 6; j++)
System.out.println(i + " " + j);
In the inner loop, I started each iteration with the value of i instead of 1. What does this do? In the first iteration, you will print out nothing but unique pairs. BUT, on subsequent iterations, I need to eliminate a number that was already rolled. I do this by starting the inner loop with the current starting value of i. This guarantees no duplicate pairs. For example, in the second iteration, I eliminate the value of "1" by starting with current i value of 2; which eliminates the duplicate 2 1 pair and starts the second round with 2 2 instead. By the time you reach the last iteration, only the one remaining unique pair will be printed out: 6 6.
This is simple enough. But, how does adding another dice affect the solution? Take the same approach. Start the inner-most loop with the value of the counter variable of the immediate outer loop like this:
for (int i = 1; i <= 6; i++)
for (int j = i; j <= 6; j++)
for (int k = j; k <= 6; k++)
System.out.println(i + " " + j + " " + k);
This solution prints out only 56 combinations rather than 216 (6^3). That is a HUGE performance improvement. Project that improvement with more inner loops.
# Answer 2
if order does not mater, try:
for (int i = 1; i < 7; i++) {
for (int m = i; m < 7; m++) {
for (int j = m; j < 7; j++) {
...
same for all dice, posted code showing only the 3 first ones
that is, the initial value is never less then the value of previous dice - result will kind of be sorted.
(considering only 2 dice, for example, this will eliminate results like 2 1 or 3 1, but allow 1 1, 1 2 and 1 3)
Note: easier to read (IMO): for (int i = 1; i <= 6; i++) {