// Erika Wolfe, CSE 143 // Examples of recursive backtracking // Added a check in diceSum to avoid exploring // dead end paths. import java.util.*; public class Backtracking2 { public static void main(String[] args) { // fourAB(); // diceRoll(2); diceSum(2, 7); } // This method will print all strings of length 4 composed of // only a's and b's public static void fourAB() { fourAB(""); } // This method will print all strings of length 4 composed of // only a's and b's with the prefix soFar private static void fourAB(String soFar) { if (soFar.length() == 4) { System.out.println(soFar); } else { // soFar = soFar + "a"; fourAB(soFar + "a"); fourAB(soFar + "b"); } } // Prints all possible outcomes of rolling the given // number of six-sided dice in [#, #, #] format. // pre: dice >= 0 public static void diceRoll(int dice) { diceRoll(dice, new ArrayList()); } // Prints all possible outcomes of rolling the given // number of six-sided dice in [#, #, #] format. // chosen contains the dice we've chosen so far // pre: dice >= 0 private static void diceRoll(int dice, List chosen) { // how do I know when I'm done? if (dice == 0) { System.out.println(chosen); } else { // how do I make a single choice? what are the options? for (int i = 1; i <= 6; i++) { chosen.add(i); // choose diceRoll(dice - 1, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose } } } // 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, 0, new ArrayList()); } private static void diceSum(int dice, int sum, int sumSoFar, List chosen) { // how do I know when I'm done? if (dice == 0) { if (sum == sumSoFar) { System.out.println(chosen); } } else if (sumSoFar + dice <= sum && sumSoFar + dice * 6 >= sum) { // how do I make a single choice? what are the options? for (int i = 1; i <= 6; i++) { chosen.add(i); // choose diceSum(dice - 1, sum, sumSoFar + i, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose } } } }