Skip to content

Commit 49a49c6

Browse files
author
Vishal Sharma
committed
added egg-dropping puzzel in c++
1 parent 9c37372 commit 49a49c6

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

C++/egg-droping-puzzel.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// A utility function to get
5+
// maximum of two integers
6+
int max(int a, int b)
7+
{
8+
return (a > b) ? a : b;
9+
}
10+
11+
// Function to get minimum
12+
// number of trials needed in worst
13+
// case with n eggs and k floors
14+
int eggDrop(int n, int k)
15+
{
16+
// If there are no floors,
17+
// then no trials needed.
18+
// OR if there is one floor,
19+
// one trial needed.
20+
if (k == 1 || k == 0)
21+
return k;
22+
23+
// We need k trials for one
24+
// egg and k floors
25+
if (n == 1)
26+
return k;
27+
28+
int min = INT_MAX, x, res;
29+
30+
// Consider all droppings from
31+
// 1st floor to kth floor and
32+
// return the minimum of these
33+
// values plus 1.
34+
for (x = 1; x <= k; x++) {
35+
res = max(
36+
eggDrop(n - 1, x - 1),
37+
eggDrop(n, k - x));
38+
if (res < min)
39+
min = res;
40+
}
41+
42+
return min + 1;
43+
}
44+
45+
// Driver program to test
46+
// to printDups
47+
int main()
48+
{
49+
int n = 2, k = 10;
50+
cout << "Minimum number of trials "
51+
"in worst case with "
52+
<< n << " eggs and " << k
53+
<< " floors is "
54+
<< eggDrop(n, k) << endl;
55+
return 0;
56+
}
57+

0 commit comments

Comments
 (0)