// Hunter Schafer, CSE 143 // Examples of recursive backtracking import java.util.*; public class Backtracking2 { public static void main(String[] args) { diceSum(2, 7); } // Prints all possible outcomes of rolling the given // number of six-sided dice that add up to exactly // the given sum, in [#, #, #] format. public static void diceSum(int dice, int sum) { diceSum(dice, sum, new ArrayList()); } // Prints all the possible outcomes of rolling the given number // of six-sided dice that add up to exactly the given sum, in [#, #, #] format. // sumSoFar is the sum of all the numbers in chosen. chosen is // the prefix for all the answers printed. private static void diceSum(int dice, int sum, int sumSoFar, List chosen) { // Hunter: Now with both checks on the else-if, we can go back to having an && in our base case if (dice == 0 && sumSoFar == sum) { System.out.println(chosen); } else if (sumSoFar + dice <= sum && sumSoFar + 6 * dice >= sum) { // Hunter: added a check to make sure it was even possible to make it to the desired sum for (int i = 1; i <= 6; i++) { // for all possible choices chosen.add(i); // choose diceSum(dice - 1, sum, sumSoFar + i, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose } } } }