// Allison Obourn // CSE 143 - lecture 17 // 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()); } // 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) { if(dice == 0) { if(sum == 0) { System.out.println(soFar); } } else if (sum >= dice * 1 && sum <= dice * 6) { for(int i = 1; i <= 6; i++) { soFar.add(i); diceSum(dice - 1, sum - i, soFar); soFar.remove(soFar.size() - 1); } } } }