Skip to content

Commit e611ec7

Browse files
committed
Egg Dropping Problem.
1 parent cf607df commit e611ec7

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

python/dynamic/egg_drop.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Problem Statement
3+
=================
4+
5+
Given a certain number of eggs and a certain number of floors, determine the minimum number of attempts
6+
required to find the egg breaking floor.
7+
8+
Analysis
9+
--------
10+
11+
* Dynamic Programming Time Complexity: O(eggs * num_floors^2)
12+
* Recursive Solution: Exponential
13+
14+
Video
15+
-----
16+
17+
* https://youtu.be/3hcaVyX00_4
18+
19+
Reference
20+
---------
21+
22+
* http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
23+
24+
"""
25+
26+
27+
def min_attempts_egg_drop(eggs, floors):
28+
num_eggs = eggs + 1
29+
num_floors = floors + 1
30+
31+
T = [[floor if egg == 1 else 0 for floor in range(num_floors)] for egg in range(num_eggs)]
32+
33+
for egg in range(2, num_eggs):
34+
for floor in range(1, num_floors):
35+
T[egg][floor] = min(1 + max(T[egg - 1][k - 1], T[egg][floor - k]) for k in range(1, floor + 1))
36+
37+
return T[num_eggs - 1][num_floors - 1]
38+
39+
40+
def min_attempts_egg_drop_recursive(eggs, floors):
41+
if eggs == 1 or floors == 0:
42+
return floors
43+
44+
min_value = float("inf")
45+
46+
for floor in range(1, floors + 1):
47+
min_value = min(min_value,
48+
1 + max(min_attempts_egg_drop_recursive(eggs - 1, floor - 1),
49+
min_attempts_egg_drop_recursive(eggs, floors - floor)))
50+
51+
return min_value
52+
53+
54+
if __name__ == '__main__':
55+
eggs = 3
56+
floors = 100
57+
expected_attempts = 9
58+
59+
assert expected_attempts == min_attempts_egg_drop(eggs, floors)
60+
61+
eggs = 2
62+
floors = 6
63+
expected_attempts = 3
64+
assert expected_attempts == min_attempts_egg_drop_recursive(eggs, floors)

0 commit comments

Comments
 (0)