Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm - Max number of grains that can be transported

Tags:

algorithm

I came across an interview question asked at Google which I can not solve:

There is a pile of N kg grains at an oasis located in a distance of D km to a town. The grains need to be transported by a camel cart whose initial location is at the oasis. The cart can carry C kg of grains at a time. The camel uses the grains as fuel while transporting them. It consumes F kg/km.

Write a function that computes the maximum amount of grains (X kg) that can be transported to the town.


I tried to use recursion but I couldn't get much further without confusing myself.

Here's what I have so far:

number of transports = N / C

fuel amount for distance D = D * F

X = N - ((number of transports) * 2 * (fuel amount for distance D))
like image 831
user1684308 Avatar asked Nov 19 '12 02:11

user1684308


1 Answers

Assuming that N, D, C and F are inputs, -

float computeMaxGrains(float N, float D, float C, float F)
{
    //Case when the cart can carry all grains at once
    if(N <= C)
    {
        float remainingGrains = N - D*F;
        if(remainingGrains >= 0)
        {
            return remainingGrains;
        }
        else
        {
            //out of fuel
            return 0;
        }
    }

    // Grains consumed per Km = (Total Number of Trips) * F
    // Total Number of Trips = 2*(N/C) + 1
    float grainsConsumedPerKm = (float) (2*(Math.floor(N/C)) + 1);

    // Remaining grains after Camels fuel = C*(N/C - 1)
    float remainingGrains = (float) (C*(Math.floor(N/C)));

    // Distance that the Camel is able to travel before the camel is 
    // 1 less round trip = 
    // (N - Remaining Grains) / grainsConsumedPerKm
    // From equation N - (grainsConsumedPerKm * distanceTravelled) = 
    // Remaining Grains
    float distanceTravelled = (N - remainingGrains) / grainsConsumedPerKm;

    if(distanceTravelled >= D)
    {
        return N - (D * grainsConsumedPerKm);
    }

    //Use recursion for every 1 less round trip
    return computeMaxGrains(remainingGrains, D-distanceTravelled, C, F);
}
like image 124
Tushar Gupta Avatar answered Sep 28 '22 07:09

Tushar Gupta