File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 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+ return eggFloor [n ][m ];
42+
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+
51+ int result = minTrials (n , m );
52+ System .out .println (result );
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments