// Helene Martin, CSE 143 // Demonstrates using recursive backtracking to identify and print all possible dice roll // values for a given number of dice and all rolls that add up to a given sum. import java.util.*; // diceSum(3, 7); // - no pruning: 259 calls // - pruning: 133 calls // diceSum(5, 7); // - no pruning: 9331 // - pruning: 343 public class Dice { public static void main(String[] args) { diceRoll(3); // diceSum(3, 7); } // 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()); } private static void diceRoll(int dice, List soFar) { if (dice == 0) { System.out.println(soFar); } else { System.out.println("> " + soFar); // beginning of a new call // set a value for first die // remove a die // recurse for (int i = 1; i <= 6; i++) { soFar.add(i); diceRoll(dice - 1, soFar); soFar.remove(soFar.size() - 1); } } } // 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(), 0); } private static void diceSum(int dice, int sum, List soFar, int sumSoFar) { // int sumSoFar = 0; // for (int value : soFar) { // sumSoFar += value; // } if (dice == 0) { if (sumSoFar == sum) { System.out.println(soFar); } } else if (sumSoFar + dice <= sum && sumSoFar + dice * 6 >= sum) { for (int i = 1; i <= 6; i++) { soFar.add(i); diceSum(dice - 1, sum, soFar, sumSoFar + i); soFar.remove(soFar.size() - 1); } } } }