...

/

Solution: Egg Dropping Problem

Solution: Egg Dropping Problem

Explore various approaches to solve the egg dropping problem in detail.

Solution 1: Brute force

using System;
class Program
{
/// <summary>
/// Figures out which floor of the skyscraper that the eggs can be safely dropped from without breaking.
/// </summary>
/// <param name="eggs">Number of eggs.</param>
/// <param name="floors">Number of stories of the skyscraper.</param>
/// <returns>The floor from which eggs can be safely dropped without breaking.</returns>
public static int EggDrop(int eggs, int floors)
{
// If there are no eggs, then there can't be any tries
if (eggs <= 0)
{
return 0;
}
// If there are no floors, then no trials needed. OR if there is
// one floor, one trial needed.
if (floors == 1 || floors == 0)
{
return floors;
}
// We need k trials for one egg and k floors
if (eggs == 1)
{
return floors;
}
int min = int.MaxValue;
int res = 0;
// Consider all droppings from 1st floor to kth floor and
// return the minimum of these values plus 1.
for (int i = 1; i <= floors; i++)
{
res = Math.Max(EggDrop(eggs - 1, i - 1), EggDrop(eggs, floors - i));
if (res < min)
{
min = res;
}
}
return min + 1;
}
// Driver code to test the above method
public static void Main(string[] args)
{
Console.WriteLine(EggDrop(2, 13));
}
}

Explanation

When we drop an egg from the floor i, there can be two cases: either the egg breaks or the egg doesn’t break.

  • If the egg breaks after dropping from the ithi^{th} floor, then we only need to check for floors lower than i with the remaining eggs, so the problem reduces to i - 1 floors and n - 1 eggs.
  • If the egg doesn’t break after dropping from the
...