Skip to content

Commit b8cd15c

Browse files
dicethrow.py
A python solution of dice throw problem.
1 parent e24c675 commit b8cd15c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Dynamic Programming/dicethrow.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Python program
2+
# The main function that returns number of ways to get sum 'x'
3+
# with 'n' dice and 'm' with m faces.
4+
5+
6+
def findWays(f, d, s):
7+
# Create a table to store results of subproblems. One extra
8+
# row and column are used for simpilicity (Number of dice
9+
# is directly used as row index and sum is directly used
10+
# as column index). The entries in 0th row and 0th column
11+
# are never used.
12+
mem = [[0 for i in range(s+1)] for j in range(d+1)]
13+
# Table entries for no dices
14+
# If you do not have any data, then the value must be 0, so the result is 1
15+
mem[0][0] = 1
16+
# Iterate over dices
17+
for i in range(1, d+1):
18+
19+
# Iterate over sum
20+
for j in range(1, s+1):
21+
# The result is obtained in two ways, pin the current dice and spending 1 of the value,
22+
# so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we
23+
# would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations
24+
# that pin the remaining j-1's. But there is a way, when "j-f-1> = 0" we would be adding
25+
# extra combinations, so we remove the combinations that only pin the extrapolated dice face and
26+
# subtract the extrapolated combinations.
27+
mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]
28+
if j - f - 1 >= 0:
29+
mem[i][j] -= mem[i - 1][j - f - 1]
30+
return mem[d][s]
31+
32+
# Driver code
33+
34+
print(findWays(4, 2, 1))
35+
print(findWays(2, 2, 3))
36+
print(findWays(6, 3, 8))
37+
print(findWays(4, 2, 5))
38+
print(findWays(4, 3, 5))
39+
40+
# This code is contributed by ankush_953

0 commit comments

Comments
 (0)