Ajeet Ganga
Ajeet Ganga

Reputation: 8653

Given N marbles and M floors, find the algorithm to find the lowest floor from which marble would break

It is related to this questioN : Two marbles and a 100 story building BUT it is not the same ... We are to figure out best algorithm to figure out, strategy to minimize maximum drops required to find lowest floor ..

Here is what I have on top of my mind

The last marble has to be dropped in stepwise fashion

Rest of the marbles will choose a hop (say hop-n)

e.g.. So when N = 2, M = 100, We know that maximum drops=14 and hop-1 = the floor from which first marble will be dropped for very first time.

Upvotes: 3

Views: 1830

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

Number of floors F that can be explored with M marbles and D drops is

F(0,D) = 0 /* no marbles, no results */
F(M,0) = 0 /* no drops, no results */

F(M,D) = 1 + /* we drop a marble once... */
    F(M-1,D-1) + /* it breaks ... */
    F(M,D-1) /* or it doesn't */

This function is a reverse of what you want to calculate, but this is not a problem. The function is monotonic so just do a binary search in the result space.

Upvotes: 4

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13890

Here is simple brute-force solution written in Java:

/**
 * Return maximum number of floors that could be checked with given number
 * of marbles and drops.
 */
private static int getMaximumFloors (int marblesCount, int dropsCount)
{
    if (marblesCount == 0) return 0;
    else
    {
        int result = 0;

        for (int i = 0; i < dropsCount; i++)
        {
            result += getMaximumFloors (marblesCount - 1, i) + 1;
        }

        return result;
    }
}

/**
 * Return minimum number of drops that is definitely enough to check
 * given number of floors having given number of marbles.
 */
private static int getMinimumDrops (int marblesCount, int floorsCount)
{
    int dropsCount = 0;
    while (getMaximumFloors (marblesCount, dropsCount) < floorsCount)
        dropsCount += 1;
    return dropsCount;
}

public static void main (String [] args)
{
    System.out.println (getMinimumDrops (2, 100));
}

It should be easy to port it to C/C++.

Here are some results:

2 marbles, 100 floors -> 14
3 marbles, 100 floors -> 9
4 marbles, 100 floors -> 8
5 marbles, 100 floors -> 7
6 marbles, 100 floors -> 7

Upvotes: 6

Related Questions