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 ofD
km to a town. The grains need to be transported by a camel cart whose initial location is at the oasis. The cart can carryC
kg of grains at a time. The camel uses the grains as fuel while transporting them. It consumesF
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))
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With