// CSE 143, Winter 2012 // This program uses recursive backtracking to print all sets of dice // roll values for a given number of dice, and all rolls of dice that // add up to a given sum. import java.util.*; public class Dice { public static void main(String[] args) { diceRoll(2); System.out.println(); diceSum(3, 7); } // Prints all possible outcomes of rolling the given // number of six-sided dice in [#, #, #] format. public static void diceRoll(int dice) { List chosen = new ArrayList(); diceRoll(dice, chosen); // initially we have chosen nothing } // Private recursive helper to implement diceRoll logic. // Adds a 'chosen' parameter of a list representing // what dice values have been chosen so far. private static void diceRoll(int dice, List chosen) { if (dice == 0) { // Base case: nothing left to roll. Print what we chose. System.out.println(chosen); } else { // Recursive case: dice >= 1. // Try choosing all possible values for the next 1 die. for (int i = 1; i <= 6; i++) { chosen.add(i); // choose diceRoll(dice - 1, chosen); // explore chosen.remove(chosen.size() - 1); // un-choose } } } // Prints all possible outcomes of rolling the given // number of six-sided dice that add up to exactly // the given sum, in [#, #, #] format. // Example: diceSum(3, 10) will print [1, 5, 4], [3, 4, 4], ... public static void diceSum(int dice, int desiredSum) { List chosen = new ArrayList(); diceSum(dice, desiredSum, chosen, 0); } // Private recursive helper to implement diceSum logic. // Adds a 'chosen' parameter of a list representing what dice values // have been chosen so far, and a 'sumSoFar' parameter for the sum of // all the dice rolls made so far. // (The sumSoFar parameter avoids having to re-compute similar sums.) private static void diceSum(int dice, int desiredSum, List chosen, int sumSoFar) { if (dice == 0) { // Base case; nothing left to roll. Maybe print what we chose. if (sumSoFar == desiredSum) { System.out.println(chosen); } } else if (sumSoFar < desiredSum && sumSoFar + 6 * dice >= desiredSum) { // Recursive case: dice >= 1, and it is possible // to get the desired sum with this many dice; // try choosing all possible values for the next 1 die for (int i = 1; i <= 6; i++) { chosen.add(i); // choose diceSum(dice - 1, desiredSum, chosen, sumSoFar + i); // explore chosen.remove(chosen.size() - 1); // un-choose } } } }