Dice Throw Problem
This algorithm finds the number of ways to get summation of values on each face when all the dice are thrown.
static int** Create2DArray(int rowCount, int colCount)
{
int** arr = new int*[rowCount];
for (int i = 0; i < rowCount; ++i)
arr[i] = new int[colCount];
return arr;
}
static void Fill2DArray(int** arr, int rowCount, int colCount, int value)
{
for (int i = 0; i < rowCount; ++i)
for (int j = 0; j < colCount; ++j)
arr[i][j] = value;
}
static int FindWays(int faces, int dice, int sum)
{
int** table = Create2DArray(dice + 1, sum + 1);
Fill2DArray(table, dice + 1, sum + 1, 0);
for (int i = 1; i <= faces && i <= sum; ++i)
table[1][i] = 1;
for (int i = 2; i <= dice; ++i)
{
for (int j = 1; j <= sum; ++j)
{
for (int k = 1; k <= faces && k < j; ++k)
{
table[i][j] += table[i - 1][j - k];
}
}
}
return table[dice][sum];
}
Example
int result = FindWays(4, 3, 5);
Output
6