|
| 1 | +""" |
| 2 | +Calculate the minimum number of attempts needed in the worst case to find the |
| 3 | +critical floor from which eggs start breaking when dropped. |
| 4 | +""" |
| 5 | + |
| 6 | +# The Egg Dropping Problem is a classic dynamic programming problem. |
| 7 | +# - You are given `k` eggs and a building with `n` floors. Your goal is to determine |
| 8 | +# the minimum number of attempts required to find the highest floor `F` from which |
| 9 | +# if an egg is dropped, it will break. If an egg breaks from floor `F`, it will |
| 10 | +# also break from any floor above `F`. The challenge is to minimize the worst-case |
| 11 | +# number of attempts. |
| 12 | + |
| 13 | + |
| 14 | +def egg_dropping(eggs: int, floors: int) -> int: |
| 15 | + """ |
| 16 | + Calculate the minimum number of attempts needed in the worst case for `eggs` |
| 17 | + and `floors` using dynamic programming. |
| 18 | +
|
| 19 | + >>> egg_dropping(1, 5) |
| 20 | + 5 |
| 21 | + >>> egg_dropping(2, 6) |
| 22 | + 3 |
| 23 | + >>> egg_dropping(2, 10) |
| 24 | + 4 |
| 25 | + """ |
| 26 | + |
| 27 | + # Base case: No floors require 0 trials, one floor requires 1 trial. |
| 28 | + if floors in (0, 1): |
| 29 | + return floors |
| 30 | + if eggs == 1: |
| 31 | + return floors |
| 32 | + |
| 33 | + # Create a DP table to store the results of subproblems. |
| 34 | + dp = [[0 for _ in range(floors + 1)] for _ in range(eggs + 1)] |
| 35 | + |
| 36 | + # Fill the base cases for one egg (i.e., we need `i` attempts for `i` floors). |
| 37 | + for i in range(1, floors + 1): |
| 38 | + dp[1][i] = i |
| 39 | + |
| 40 | + # Compute the minimum number of trials in the worst case for each combination. |
| 41 | + for e in range(2, eggs + 1): |
| 42 | + for f in range(1, floors + 1): |
| 43 | + dp[e][f] = 10**9 # Initialize to infinity. |
| 44 | + for x in range(1, f + 1): |
| 45 | + res = 1 + max(dp[e - 1][x - 1], dp[e][f - x]) |
| 46 | + dp[e][f] = min(dp[e][f], res) |
| 47 | + |
| 48 | + return dp[eggs][floors] |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + print("\n********* Egg Dropping Problem Using Dynamic Programming ************\n") |
| 53 | + print("\n*** Enter -1 at any time to quit ***") |
| 54 | + print("\nEnter the number of eggs and floors separated by a space: ", end="") |
| 55 | + try: |
| 56 | + while True: |
| 57 | + input_data = input().strip() |
| 58 | + if input_data == "-1": |
| 59 | + print("\n********* Goodbye!! ************") |
| 60 | + break |
| 61 | + else: |
| 62 | + eggs, floors = map(int, input_data.split()) |
| 63 | + print( |
| 64 | + f"The minimum number of attempts required with {eggs} eggs and " |
| 65 | + f"{floors} floors is:" |
| 66 | + ) |
| 67 | + print(egg_dropping(eggs, floors)) |
| 68 | + print("Try another combination of eggs and floors: ", end="") |
| 69 | + except NameError, ValueError: |
| 70 | + print("\n********* Invalid input, goodbye! ************\n") |
0 commit comments