# Number of Dice Rolls With Target Sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have d dice, and each die has f number of faces numbered 1, 2, ..., f. We have to find the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equal to the target. So if the input is like d = 2, f = 6, target = 7, then the output will be 6. So if we throw each dice with 6 faces, then there are 6 ways to get sum 6, as 1 + 6, 2 + 5, 3 + 3, 4 + 3, 5 + 2, 6 + 1.

To solve this, we will follow these steps −

• m := 1e9 + 7
• make a table dp of order d x (t + 1), and fill this with 0
• for i in range 0 to d – 1
• for j in range 0 to t
• if i = 0, then dp[i, j] := 1 when j in range 1 to f, otherwise 0
• otherwise
• for l in range 1 to f
• if j – l > 0, then dp[i, j] := dp[i, j] + dp[i – 1, j - l], and dp[i,j] := dp[i, j] mod m
• return dp[d – 1, t] mod m

## Example(Python)

Let us see the following implementation to get better understanding −

Live Demo

class Solution(object):
def numRollsToTarget(self, d, f, t):
mod = 1000000000+7
dp =[[0 for i in range(t+1)] for j in range(d)]
for i in range(d):
for j in range(t+1):
if i == 0:
dp[i][j] = 1 if j>=1 and j<=f else 0
else:
for l in range(1,f+1):
if j-l>0:
dp[i][j]+=dp[i-1][j-l]
dp[i][j]%=mod
return dp [d-1][t] % mod
ob = Solution()
print(ob.numRollsToTarget(2,6,7))

## Input

2
6
7

## Output

6
Published on 17-Mar-2020 10:21:18