Program to Find Out the Probability of Having n or Fewer Points in Python

Suppose we are playing a unique game with three values n, k, and h. We start from 0 points, then we can select a number randomly between 1 and h (inclusive) and we will get that many points. We stop when we have scored a minimum of k points. We have to find the probability that we have n or fewer points when we stop.

So, if the input is like n = 2, k = 2, h = 10, then the output will be 0.11.

Algorithm Steps

To solve this, we will follow these steps:

  • Define a recursive function dp(path) that calculates probability from current path
  • Base cases:
    • If path == k - 1, return min(n - k + 1, h) / h
    • If path > n, return 0 (exceeded target)
    • If path >= k, return 1 (reached minimum points)
  • Otherwise, use recursive formula with probability calculations

Implementation

class Solution:
    def solve(self, n, k, h):
        # Edge cases
        if not k: 
            return 1
        if n < k: 
            return 0
            
        def dp(path):
            # Base case: one step before minimum
            if path == k - 1:
                return min((n - k + 1), h) / h
            
            # If we exceeded our target points
            if path > n:
                return 0
            
            # If we reached minimum points
            if path >= k:
                return 1
            
            # Recursive case with probability calculation
            return dp(path + 1) - (dp(path + h + 1) - dp(path + 1)) / h
        
        return dp(0)

# Test the solution
solution = Solution()
result = solution.solve(2, 2, 10)
print(f"Probability: {result}")
Probability: 0.11

Example with Different Parameters

Let's test with different values to understand the behavior ?

solution = Solution()

# Test case 1: n=2, k=2, h=10
print(f"n=2, k=2, h=10: {solution.solve(2, 2, 10)}")

# Test case 2: n=5, k=3, h=6
print(f"n=5, k=3, h=6: {solution.solve(5, 3, 6)}")

# Test case 3: n=10, k=5, h=8
print(f"n=10, k=5, h=8: {solution.solve(10, 5, 8)}")
n=2, k=2, h=10: 0.11
n=5, k=3, h=6: 0.6944444444444444
n=10, k=5, h=8: 0.9453125

How It Works

The algorithm uses dynamic programming with memoization to calculate probabilities:

  • Each recursive call represents a state with current points
  • The probability is calculated based on all possible outcomes from rolling 1 to h
  • Base cases handle boundary conditions efficiently
  • The recursive formula accounts for the uniform distribution of dice rolls

Conclusion

This solution efficiently calculates the probability of scoring n or fewer points in the game using dynamic programming. The recursive approach with proper base cases handles all edge conditions and provides accurate probability calculations.

Updated on: 2026-03-25T14:04:31+05:30

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements