Reputation: 53
There is a problem called: Tortoise racing.
The question is:
Two tortoises named A and B must run a race. A starts with an average speed of 720 feet per hour. Young B knows she runs faster than A, and furthermore has not finished her cabbage.
When she starts, at last, she can see that A has a 70 feet lead but B's speed is 850 feet per hour. How long will it take B to catch A?
More generally: given two speeds v1 (A's speed, integer > 0) and v2 (B's speed, integer > 0) and a lead g (integer > 0) how long will it take B to catch A?
The result will be an array [hour, min, sec] which is the time needed in hours, minutes and seconds (round down to the nearest second) or a string in some languages.
If v1 >= v2 then return nil, nothing, null, None or {-1, -1, -1} for C++, C, Go, Nim, [] for Kotlin or "-1 -1 -1".
Examples: (form of the result depends on the language)
race(720, 850, 70) => [0, 32, 18] or "0 32 18"
race(80, 91, 37) => [3, 21, 49] or "3 21 49"
I tried to solve it like this:
public static int[] race(int v1, int v2, int g) {
int v3 = v2 - v1;
double time = (double )g / (double)v3;
int result[] = new int[3];
if (v2 > v1) {
if (time > 1) {
while (time > 10) {
time /= 10;
}
result[0] = (int) time;
result[1] = (int) ((time - result[0]) * 60);
result[2] = (int) ((((time - result[0]) * 60) - result[1]) * 60);
System.out.print(result[0] + " " + result[1] + " " + result[2]);
} else {
result[0] = 0;
result[1] = (int) (time * 60);
result[2] = (int) (((time * 60) - result[1]) * 60);
System.out.print(result[0] + " " + result[1] + " " + result[2]);
}
}
else {
return null;
}
return result;
}
but it keeps failing on test cases, could you please help me?
Upvotes: 1
Views: 2596
Reputation: 270
Probably you could try following code,
public static int[] race(int v1, int v2, int g){
if(v1 >= v2)
return null; //B will never catch A
int speedDifference = (v2 - v1);
int resultInSeconds = g * 3600 / speedDifference; //*3600 to get in seconds
int[] result = {resultInSeconds/3600, resultInSeconds%3600/60, resultInSeconds%3600%60};
return result;
}
Upvotes: 2
Reputation: 2352
Check Below code :
public class Tortoise {
public static int[] race(int v1, int v2, int g) {
if (v1 >= v2)
return null;
int seconds = (g * 3600) / (v2 - v1);
return new int[]{seconds / 3600, (seconds % 3600) / 60, seconds % 60};
}
public static void main(String[] args) {
Tortoise.race(720, 850, 70);
}
}
Upvotes: 9