Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw 2 eggs from a building and find the floor F with ~c*sqrt(F) throws?

I am reading Robert Sedgewick's algorithms 4th edition book, and he has the following task:

Suppose that you have an N-story building and 2 eggs. Suppose also that an egg is broken if it is thrown off floor F or higher, and unbroken otherwise. Your cost model is the number of throws. Devise a strategy to determine F such that the number of throws ~c √ F for some constant c.

The first part of the task is to find F in 2 √ N steps, and here's a solution for that:

Solution to Part 1:

  • To achieve 2 * sqrt(N), drop eggs at floors sqrt(N), 2 * sqrt(N), 3 * sqrt(N), ..., sqrt(N) * sqrt(N). (For simplicity, we assume here that sqrt(N) is an integer.)
  • Let assume that the egg broke at level k * sqrt(N).
  • With the second egg you should then perform a linear search in the interval (k-1) * sqrt(N) to k * sqrt(N).
  • In total you will be able to find the floor F in at most 2 * sqrt(N) trials.

He also provides a hint for the ~c √ F part (part 2):

Hint for Part 2: 1 + 2 + 3 + ... k ~ 1/2 k^2.

So what is the algorithm to do it in ~c √ F steps?

like image 670
Pavel Avatar asked Apr 30 '15 10:04

Pavel


People also ask

Which floor is the floor on which two eggs are sure to break?

We see then that the first egg should be thrown finally from the 99th floor, previously from 99–2=97, previously from 97–3=94, 90, 85, 79, 72, 64, 55, 45, 34, 22 and the 9th floor. This is an optimal solution!

What is the solution to the problem with 100 storeys and 2 eggs?

First solution is linear search strategy which is very straightforward if we don't care about number of drops. We can start dropping egg from floor 1, floor 2, floor 3 and continue till floor 100 until we find the floor N. In worst case it will take 100 drops if egg breaks only at the last (100th) floor.

How would you determine what the maximum floor you can drop an egg off of a 50 floor build without the egg breaking?

Answer: The easiest way to do this would be to start from the first floor and drop the egg. If it doesn't break, move on to the next floor. If it does break, then we know the maximum floor the egg will survive is 0.

How do you throw an egg from a building without breaking it?

To drop an egg without breaking it, wrap the egg in wet paper towels and place it in a plastic bag of puff rice cereal. Fill 4 small bags with puffed cereal too, then put all the bags into 1 large container. You can also wrap the egg in packing material, like bubble wrap, packing peanuts, or inflated plastic packets.


1 Answers

Drop first egg from floors 1, 3, 6, ... (the partials sums of 1, 2, 3, ...). Then do linear search between last two floors.

like image 168
Henrik Avatar answered Oct 07 '22 00:10

Henrik