TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
egg_dropping_puzzle.cpp
1/* Function to get minimun number of trials needed
2 * in worst case with n eggs and k floors
3 */
4
5#include <climits>
6#include <iostream>
7#include <vector>
8
9using namespace std;
10
11int eggDrop(int n, int k) {
12 std::vector<std::vector<int> > eggFloor(n + 1, std::vector<int>(k + 1));
13
14 int result;
15
16 for (int i = 1; i <= n; i++) {
17 eggFloor[i][1] = 1; // n eggs..1 Floor
18 eggFloor[i][0] = 0; // n eggs..0 Floor
19 }
20
21 // Only one egg available
22 for (int j = 1; j <= k; j++) {
23 eggFloor[1][j] = j;
24 }
25
26 for (int i = 2; i <= n; i++) {
27 for (int j = 2; j <= k; j++) {
28 eggFloor[i][j] = INT_MAX;
29 for (int x = 1; x <= j; x++) {
30 // 1+max(eggBreak[one less egg, lower floors],
31 // eggDoesntBreak[same # of eggs, upper floors]);
32 result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
33 if (result < eggFloor[i][j])
34 eggFloor[i][j] = result;
35 }
36 }
37 }
38
39 return eggFloor[n][k];
40}
41
42int main() {
43 int n, k;
44 cout << "Enter number of eggs and floors: ";
45 cin >> n >> k;
46 cout << "Minimum number of trials in worst case: " << eggDrop(n, k) << endl;
47 return 0;
48}
double k(double x)
Another test function.
uint64_t result(uint64_t n)
int main()
Main function.
#define endl