// Jeremy Lipschutz // Showing an application of recursion, brute-force exploring // of possibilities import java.util.*; public class RecursiveBacktracking { public static void main(String[] args) { //sillyHangman(3); //diceRoll(3); diceSum(3, 10); } // Prints all strings of the given length consisting of a's and b's public static void sillyHangman(int length) { sillyHangman(length, ""); } private static void sillyHangman(int length, String decisions) { if(decisions.length() == length) { System.out.println(decisions); } else { sillyHangman(length, decisions + "a"); sillyHangman(length, decisions + "b"); /* // We can change the test for this for-loop such that we choose not only a's and b's // but also more letters like the whole alphabet for(char c = 'a'; c <= 'b'; c++) { // For each decision we have we can recur on this choice sillyHangman(length, decisions + c); } */ } } /* Iterative solution that does not scale with length :( public static void sillyHangman(int length) { for(char c1 = 'a'; c1 <= 'b'; c1++) { for(char c2 = 'a'; c2 <= 'b'; c2++) { for(char c3 = 'a'; c3 <= 'b'; c3++) { for(char c4 = 'a'; c4 <= 'b'; c4++) { System.out.println("" + c1 + c2 + c3 + c4); } } } } } */ // Assumes that n >= 0 // Prints all possible outcomes of rolling the given number of // 6-sided dice in the format [#, #, #] public static void diceRoll(int n) { diceRoll(new ArrayList(), n); } // 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(List chosen, int n) { if(chosen.size() == n) { System.out.println(chosen); } else { for(int i = 1; i <= 6; i++) { // for each option 1-6 chosen.add(i); // CHOOSE diceRoll(chosen, n); // EXPLORE chosen.remove(chosen.size() - 1); // UNCHOOSE } } } // Assumes that n >= 0 // Prints all possible outcomes of rolling the given number of // 6-sided dice in the format [#, #, #] that add up to the given sum public static void diceSum(int n, int sum) { diceSum(new ArrayList(), n, sum); } // 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 // sum represents the remaining sum that we have left to roll private static void diceSum(List chosen, int remaining, int sum) { if(remaining == 0 && sum == 0) { System.out.println(chosen); } else if(sum >= remaining && sum <= remaining * 6) { for(int i = 1; i <= 6; i++) { // for each option 1-6 chosen.add(i); // CHOOSE diceSum(chosen, remaining - 1, sum - i); // EXPLORE chosen.remove(chosen.size() - 1); // UNCHOOSE } } } }