// CSE 143, Summer 2012 // 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) { ArrayList list = new ArrayList(); diceRoll(dice, list); } // 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, ArrayList 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 n) { ArrayList list = new ArrayList(); diceSum(dice, n, list, 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 n, ArrayList chosen, int sumSoFar) { if (dice == 0) { // Base case; nothing left to roll. Maybe print what we chose. if (sumSoFar == n) { System.out.println(chosen); } } else if (sumSoFar < n && sumSoFar + 6 * dice >= n){ // 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++) { //choose chosen.add(i); sumSoFar += i; //explore diceSum(dice - 1, n, chosen, sumSoFar); //unchoose chosen.remove(chosen.size() - 1); sumSoFar -= i; } } } }