|
| 1 | +// Given N dice each with M faces, numbered from 1 to M, find the number of ways to get sum X. |
| 2 | +// X is the summation of values on each face when all the dice are thrown. |
| 3 | + |
| 4 | +/* The Naive approach is to find all the possible combinations of values from n dice and |
| 5 | +keep on counting the results that sum to X. This can be done using recursion. */ |
| 6 | + |
| 7 | +// The above recursion solution exhibits overlapping subproblems. |
| 8 | + |
| 9 | +/* Hence, storing the results of the solved sub-problems saves time. |
| 10 | +And it can be done using Dynamic Programming(DP). |
| 11 | +Following is implementation of Dynamic Programming approach. */ |
| 12 | + |
| 13 | + |
| 14 | +// Code ----> |
| 15 | +// Java program to find number of ways to get sum 'x' with 'n' |
| 16 | +// dice where every dice has 'm' faces |
| 17 | +import java.util.*; |
| 18 | +import java.lang.*; |
| 19 | +import java.io.*; |
| 20 | + |
| 21 | +class DP { |
| 22 | + /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */ |
| 23 | + public static long findWays(int m, int n, int x){ |
| 24 | + |
| 25 | + /* Create a table to store the results of subproblems. |
| 26 | + One extra row and column are used for simplicity |
| 27 | + (Number of dice is directly used as row index and sum is directly used as column index). |
| 28 | + The entries in 0th row and 0th column are never used. */ |
| 29 | + long[][] table = new long[n+1][x+1]; |
| 30 | + |
| 31 | + /* Table entries for only one dice */ |
| 32 | + for(int j = 1; j <= m && j <= x; j++) |
| 33 | + table[1][j] = 1; |
| 34 | + |
| 35 | + /* Fill rest of the entries in table using recursive relation |
| 36 | + i: number of dice, j: sum */ |
| 37 | + for(int i = 2; i <= n;i ++){ |
| 38 | + for(int j = 1; j <= x; j++){ |
| 39 | + for(int k = 1; k < j && k <= m; k++) |
| 40 | + table[i][j] += table[i-1][j-k]; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return table[n][x]; |
| 45 | + } |
| 46 | + |
| 47 | + public static void main (String[] args) { |
| 48 | + System.out.println(findWays(4, 2, 1)); |
| 49 | + System.out.println(findWays(2, 2, 3)); |
| 50 | + System.out.println(findWays(6, 3, 8)); |
| 51 | + System.out.println(findWays(4, 2, 5)); |
| 52 | + System.out.println(findWays(4, 3, 5)); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +/* |
| 57 | +OUTPUT: |
| 58 | +0 |
| 59 | +2 |
| 60 | +21 |
| 61 | +4 |
| 62 | +6 |
| 63 | +*/ |
| 64 | + |
| 65 | +// Time Complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum. |
| 66 | + |
0 commit comments