Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7b65ea5

Browse files
Create egg drop dynamic programming.jl
1 parent 64ad80d commit 7b65ea5

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

‎egg drop dynamic programming.jl‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#!/usr/bin/env julia
2+
# coding: utf-8
3+
4+
# In[1]:
5+
6+
7+
#egg drop is a simple dynamic programming problem
8+
#the player is given some number of eggs
9+
#to test eggs break by free fall from which floor
10+
#more details can be found in the link below
11+
# https://www.geeksforgeeks.org/egg-dropping-puzzle-dp-11/
12+
13+
14+
# In[2]:
15+
16+
17+
#initialize
18+
num_of_floors=271
19+
num_of_eggs=3;
20+
21+
22+
# In[3]:
23+
24+
25+
#to solve this problem via dp
26+
#we test all the floor with the eggs
27+
function egg_drop(num_of_floors,num_of_eggs)
28+
29+
#create tabulation matrix
30+
tabulation=[[NaN for _ in 1:num_of_floors] for _ in 1:num_of_eggs]
31+
32+
#when u got one egg the number of attempts will always be the number of floors
33+
tabulation[1]=[ii for ii in 1:num_of_floors]
34+
35+
#ground floor doesnt break eggs as its on the ground
36+
#first floor only takes one attempt no matter how many eggs we have
37+
for i in 2:num_of_eggs
38+
tabulation[i][1]=1
39+
end
40+
41+
#since we initialize the ground floor and the first floor
42+
#the loop starts from 2
43+
for id_egg in 2:num_of_eggs
44+
for id_floor in 2:num_of_floors
45+
46+
#at the current position (id_egg,id_floor)
47+
#there are id_egg number of eggs and id_floor number of floors
48+
#we start to experiment the worst case via brute force
49+
#we drop eggs on each floor
50+
#there are id_floor*2 scenarios
51+
#each floor can be the one that breaks the egg or doesnt break the eggs
52+
#hence we compute how many trials are required for each scenario
53+
#take the maximum first to obtain worst case for each floor
54+
#and take the minimum to obtain the minimum number of trials
55+
tabulation[id_egg][id_floor]=minimum(
56+
append!([1+max(
57+
tabulation[id_egg-1][j-1],
58+
tabulation[id_egg][id_floor-j]) for j in 2:(id_floor-1)],
59+
60+
#due to index starts at 1,the last worst case has to be separated
61+
[1+tabulation[id_egg-1][id_floor-1]]))
62+
end
63+
end
64+
return tabulation[num_of_eggs][num_of_floors]
65+
end
66+
67+
68+
# In[4]:
69+
70+
71+
egg_drop(num_of_floors,num_of_eggs)
72+
73+
74+
# In[ ]:
75+
76+
77+
78+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /