I have the following Java assignment. In a board game I can roll a 6-faced dice and move forward the same number of spaces. If the goal is “n” spaces away from the starting point, how do I implement a program that calculates all possible ways there are to arrive exactly at the "n"? I'm squeezing my head but I can't find the solution, I have searched the net but nothing is what I want exactly. I know it's not that hard, I just can't find the correct way to do it.
Thanks in advance.
There are multiple ways to do this, so I'm going to keep it generic. Determine all possible permutations, storing the values. Generate a roll, getting the total. Sift through the permutations that match the total.
class Roll {
int first;
int second;
int total;
public Roll(int first, int second) {
this.first = first;
this.second = second;
this.total = first + second;
}
List<Roll> permutations = new ArrayList<>();
for (int ii = 1; ii < 7; ii++)
for (int jj = 1; jj < 7; jj++)
permutations.add(new Roll(ii,jj);
roll the dice, determine the total;
now loop through the permutations to find the
total matching the roll total. These are your combinations.
This solution doesn't handle duplicate rolls. For example 1,6 and 6,1;