// Allison Obourn // CSE 143 - lecture 16 // Prints all possible combinations of dice and all combinations // of dice that sum to a given value import java.util.*; public class Dice { public static void main(String[] args) { diceRoll(3); diceSum(3, 7); diceSum(5, 7); diceSum(15, 87); } // 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()); } // Prints all combinations of rolling the given number of // six-sided dice. // pre: dice >= 0 and soFar != null private static void diceRoll(int dice, List soFar) { if(dice == 0) { System.out.println(soFar); } else { 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. // pre: dice >= 0 public static void diceSum(int dice, int sum) { diceSum(dice, sum, new ArrayList(), 0); } // Prints all possible outcomes of rolling the given // number of six-sided dice that add up to exactly // the given sum // pre: dice >= 0 and soFar != null private static void diceSum(int dice, int sum, List soFar, int sumSoFar) { if(dice == 0) { // initially we calculated the total so far here but that slowed us down // there is no need to add up the numbers every time when we can add once // each as we recurse // int sumSoFar = 0; // for(int n : soFar) { // sumSoFar += n; //} if(sumSoFar == sum) { System.out.println(soFar); } } else if (sumSoFar + 6 * dice >= sum && sumSoFar + dice <= sum) { for(int i = 1; i <= 6; i++) { soFar.add(i); diceSum(dice - 1, sum, soFar, sumSoFar + i); soFar.remove(soFar.size() - 1); } } } }