/* * Kyle Pierce * CSE 143 * * Examples of recursive backtracking */ import java.util.*; public class Backtracking { public static void main(String[] args) { fourAB(); diceRoll(3); } // post: prints all strings of length 4 containing only a's and b's public static void fourAB() { fourAB(""); } // post: prints all strings of length 4 containing only a's and b's // that start with the given prefix soFar private static void fourAB(String soFar) { if (soFar.length() == 4) { System.out.println(soFar); } else { // recall that (soFar + "a") passes a new string as parameter // with an 'a' added to the end, but does not update the value // of soFar (since we did +, not +=), so we don't have to // remove the 'a' before making the second call fourAB(soFar + "a"); fourAB(soFar + "b"); } } // pre: dice >= 0 // post: prints all possible outcomes of rolling the given number of // 6-sided dice in the format [#, #, #] public static void diceRoll(int dice) { diceRoll(dice, new ArrayList()); } // post: prints all possible outcomes of rolling the given number of // 6-sided dice in the format [#, #, #] with chosen as the rolls // that have already been computed private static void diceRoll(int dice, List chosen) { if (dice == 0) { System.out.println(chosen); } else { for (int i = 1; i <= 6; i++) { chosen.add(i); // choose diceRoll(dice - 1, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose } } } }