// CSE 143, Autumn 2013 // 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(4); 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, new ArrayList()); } // 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); // unchoose } } } // 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) { diceSum(dice, new ArrayList(), desiredSum, 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, List chosen, int desiredSum, int sum) { if(dice == 0) { // Base case; nothing left to roll. Maybe print what we chose. if(sum == desiredSum) { System.out.println(chosen); } } else if (sum < desiredSum && sum + dice * 6 >= 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, chosen, desiredSum, sum + i); // explore chosen.remove(chosen.size() - 1); // unchoose } } } }