|
| 1 | +import javax.rmi.CORBA.Util; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.Map; |
| 4 | + |
| 5 | +/** |
| 6 | + * Write a function, throw_dice(N, faces, total), that determines how many ways it is possible to throw N dice with |
| 7 | + * some number of faces each to get a specific total. |
| 8 | + * |
| 9 | + * For example, throw_dice(3, 6, 7) should equal 15 |
| 10 | + */ |
| 11 | +public class DailyCoding272 { |
| 12 | + public static void main(String[] args) { |
| 13 | + System.out.println(numDiceThrow(3, 6, 7)==15); |
| 14 | + System.out.println(numDiceThrowEfficient(3, 6, 7)==15); |
| 15 | + } |
| 16 | + public static int numDiceThrow(int numThrows, int faces, int total) { |
| 17 | + int[] count = new int[1]; |
| 18 | + numDiceThrowHelper(numThrows, faces, total, new HashMap<>(), count, 0); |
| 19 | + return count[0]; |
| 20 | + } |
| 21 | + public static void numDiceThrowHelper(int numThrows, int faces, int total, HashMap<Integer, Integer> map, |
| 22 | + int[] count, int currThrow) { |
| 23 | + if (total == 0 && currThrow == numThrows) { |
| 24 | + count[0] = count[0]+1; |
| 25 | + return; |
| 26 | + } |
| 27 | + if (currThrow == numThrows) { |
| 28 | + return; |
| 29 | + } |
| 30 | + for (int i=1; i<=faces; i++) { |
| 31 | + if (i <= total) { |
| 32 | + int c = map.getOrDefault(i, 0); |
| 33 | + map.put(i, c+1); |
| 34 | + numDiceThrowHelper(numThrows, faces, total-i, map, count, currThrow+1); |
| 35 | + c = map.get(i); |
| 36 | + c--; |
| 37 | + if (c==0) { |
| 38 | + map.remove(i); |
| 39 | + } else { |
| 40 | + map.put(i, c); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + public static int numDiceThrowEfficient(int numThrows, int faces, int total) { |
| 46 | + //DP approach |
| 47 | + /* Sum(m, n, X) = Finding Sum (X - 1) from (n - 1) dice plus 1 from nth dice |
| 48 | + + Finding Sum (X - 2) from (n - 1) dice plus 2 from nth dice |
| 49 | + + Finding Sum (X - 3) from (n - 1) dice plus 3 from nth dice |
| 50 | + ................................................... |
| 51 | + ................................................... |
| 52 | + ................................................... |
| 53 | + + Finding Sum (X - m) from (n - 1) dice plus m from nth dice */ |
| 54 | + int[][] sums = new int[numThrows+1][total+1]; |
| 55 | + for (int i=1; i<=faces; i++) { |
| 56 | + sums[1][i] = 1; |
| 57 | + } |
| 58 | + for (int i=2; i<=numThrows; i++) { |
| 59 | + for (int j=1; j<=total; j++) { |
| 60 | + for (int k=1;k<=faces; k++) { |
| 61 | + if (k <= j) { |
| 62 | + sums[i][j] += sums[i-1][j-k]; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return sums[numThrows][total]; |
| 68 | + } |
| 69 | +} |
0 commit comments