Skip to content

Commit 9fd0548

Browse files
Merge pull request TheAlgorithms#156 from dpacmen/patch-7
Add Eggdroping puzzle
2 parents 6e3ed6c + cc4fda5 commit 9fd0548

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Dynamic Programming/EggDropping.java

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
//Dynamic Programming solution for the Egg Dropping Puzzle
2+
public class EggDropping
3+
{
4+
5+
// min trials with n eggs and m floors
6+
7+
private static int minTrials(int n, int m)
8+
{
9+
10+
int eggFloor[][] = new int[n+1][m+1];
11+
int result, x;
12+
13+
for (int i = 1; i <= n; i++)
14+
{
15+
eggFloor[i][0] = 0; // Zero trial for zero floor.
16+
eggFloor[i][1] = 1; // One trial for one floor
17+
}
18+
19+
// j trials for only 1 egg
20+
21+
for (int j = 1; j <= m; j++)
22+
eggFloor[1][j] = j;
23+
24+
// Using bottom-up approach in DP
25+
26+
for (int i = 2; i <= n; i++)
27+
{
28+
for (int j = 2; j <= m; j++)
29+
{
30+
eggFloor[i][j] = Integer.MAX_VALUE;
31+
for (x = 1; x <= j; x++)
32+
{
33+
result = 1 + Math.max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
34+
35+
//choose min of all values for particular x
36+
if (result < eggFloor[i][j])
37+
eggFloor[i][j] = result;
38+
}
39+
}
40+
}
41+
42+
return eggFloor[n][m];
43+
}
44+
45+
//testing program
46+
public static void main(String args[])
47+
{
48+
int n = 2, m = 4;
49+
//result outputs min no. of trials in worst case for n eggs and m floors
50+
int result = minTrials(n, m);
51+
System.out.println(result);
52+
}
53+
}

0 commit comments

Comments
 (0)