Program to count number of ways we can throw n dices in Python

Sometimes we need to find the number of ways to throw n dice with a specific number of faces to achieve a target total. This is a classic dynamic programming problem that can be solved efficiently using bottom-up approach.

Problem Statement

Given n dice, each with a specific number of faces, find how many ways we can throw them to get a target total. Since the answer can be very large, return the result modulo 10^9 + 7.

For example, if n = 2, faces = 6, and total = 8, there are 5 ways: (2,6), (6,2), (3,5), (5,3), and (4,4).

Algorithm

We'll use dynamic programming where dp[i] represents the number of ways to achieve sum i ?

  • Initialize a DP array of size (total + 1) with zeros

  • Set dp[face] = 1 for each possible face value (base case for single die)

  • For each additional die, update the DP array by considering all possible face values

  • Return dp[total] modulo 10^9 + 7

Implementation

class Solution:
    def solve(self, n, faces, total):
        m = 10 ** 9 + 7
        dp = [0] * (total + 1)
        
        # Base case: single die
        for face in range(1, min(faces, total) + 1):
            dp[face] = 1
        
        # For each additional die
        for i in range(n - 1):
            for j in range(total, 0, -1):
                dp[j] = sum(dp[j - f] for f in range(1, faces + 1) if j - f >= 1)
        
        return dp[-1] % m

# Test the solution
ob = Solution()
n = 2
faces = 6
total = 8
result = ob.solve(n, faces, total)
print(f"Ways to get {total} with {n} dice of {faces} faces: {result}")
Ways to get 8 with 2 dice of 6 faces: 5

How It Works

The algorithm works by building up solutions for increasing numbers of dice ?

  1. Initialization: For a single die, there's exactly one way to get each face value (1 through faces)

  2. Building up: For each additional die, we calculate new possibilities by adding each face value to existing sums

  3. Backward iteration: We iterate backward to avoid counting the same combination multiple times

Example Walkthrough

For n=2, faces=6, total=8 ?

# Step by step example
def solve_with_steps(n, faces, total):
    m = 10 ** 9 + 7
    dp = [0] * (total + 1)
    
    print("Initial DP array:", dp)
    
    # Base case
    for face in range(1, min(faces, total) + 1):
        dp[face] = 1
    print("After base case (1 die):", dp)
    
    # Add second die
    for i in range(n - 1):
        print(f"\nAdding die {i + 2}:")
        new_dp = [0] * (total + 1)
        for j in range(total, 0, -1):
            new_dp[j] = sum(dp[j - f] for f in range(1, faces + 1) if j - f >= 1)
        dp = new_dp
        print("DP array:", dp)
    
    return dp[total] % m

result = solve_with_steps(2, 6, 8)
print(f"\nFinal result: {result}")
Initial DP array: [0, 0, 0, 0, 0, 0, 0, 0, 0]
After base case (1 die): [0, 1, 1, 1, 1, 1, 1, 0, 0]

Adding die 2:
DP array: [0, 0, 1, 2, 3, 4, 5, 5, 5]

Final result: 5

Time and Space Complexity

  • Time Complexity: O(n × total × faces) - we iterate through n dice, total possible sums, and faces per die

  • Space Complexity: O(total) - we use a DP array of size total + 1

Conclusion

This dynamic programming solution efficiently counts the ways to achieve a target sum with n dice. The key insight is building up solutions incrementally, ensuring each combination is counted exactly once.

Updated on: 2026-03-25T11:02:07+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements