This is a famous puzzle problem. Suppose there is a building with n floors, if we have m eggs, then how can we find the minimum number of drops needed to find a floor from which it is safe to drop an egg without breaking it.
There some important points to remember −
- When an egg does not break from a given floor, then it will not break for any lower floor also.
- If an egg breaks from a given floor, then it will break for all upper floors.
- When an egg breaks, it must be discarded, otherwise, we can use it again.
Input and Output
Input: The number of eggs and the maximum floor. Say the number of eggs are 4 and the maximum floor is 10. Output: Enter number of eggs: 4 Enter max Floor: 10 Minimum number of trials: 4
Algorithm
eggTrialCount(eggs, floors)
Input: Number of eggs, maximum floor.
Output − Get a minimum number of trials.
Begin define matrix of size [eggs+1, floors+1] for i:= 1 to eggs, do minTrial[i, 1] := 1 minTrial[i, 0] := 0 done for j := 1 to floors, do minTrial[1, j] := j done for i := 2 to eggs, do for j := 2 to floors, do minTrial[i, j] := ∞ for k := 1 to j, do res := 1 + max of minTrial[i-1, k-1] and minTrial[i, j-k] if res < minTrial[i, j], then minTrial[i,j] := res done done done return minTrial[eggs, floors] End
Example
#include<iostream> using namespace std; int max(int a, int b) { return (a > b)? a: b; } int eggTrialCount(int eggs, int floors) { //minimum trials for worst case int minTrial[eggs+1][floors+1]; //to store minimum trials for ith egg and jth floor int res; for (int i = 1; i <= eggs; i++) { //one trial to check from first floor, and no trial for 0th floor minTrial[i][1] = 1; minTrial[i][0] = 0; } for (int j = 1; j <= floors; j++) //when egg is 1, we need 1 trials for each floor minTrial[1][j] = j; for (int i = 2; i <= eggs; i++) { //for 2 or more than 2 eggs for (int j = 2; j <= floors; j++) { //for second or more than second floor minTrial[i][j] = INT_MAX; for (int k = 1; k <= j; k++) { res = 1 + max(minTrial[i-1][k-1], minTrial[i][j-k]); if (res < minTrial[i][j]) minTrial[i][j] = res; } } } return minTrial[eggs][floors]; //number of trials for asked egg and floor } int main () { int egg, maxFloor; cout << "Enter number of eggs: "; cin >> egg; cout << "Enter max Floor: "; cin >> maxFloor; cout << "Minimum number of trials: " << eggTrialCount(egg, maxFloor); }
Output
Enter number of eggs: 4 Enter max Floor: 10 Minimum number of trials: 4