Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Number line jumps.
The problem
The solution
To start our solution, let's define the function that will receive the input parameters: kagaroo
, where x1
is the initial position of the first kangaroo, v1
the jumping speed of the first kangaroo, x2
the initial position of the second kangaroo and v2
the jumping speed of the second kangaroo:
function kagaroo(x1, v1, x2, v2) {}
Let's start by checking whether the first kangaroo has a greater speed than the second kangaroo:
if (v1 > v2) {}
If v2
is greater than v1
, it is impossible for the first kangaroo to reach the second, so the function returns NO
:
else {
return "NO";
}
Later we will determine the initial distance between the two kangaroos, in the constant initialDistance
. If x2
is greater than x1
it indicates that the first kangaroo is behind the second, so the difference will be positive. Otherwise, the difference will be negative:
const initialDistance = x2 - x1;
Now let's calculate the speed difference, in the constant speedDifference
. To do this, let's subtract v1
from v2
:
const speedDifference = v1 - v2;
After calculating the initial distance difference (initialDistance
) and determining the speed difference (speedDifference
), we will validate whether initialDistance
is divisible by speedDifference
. If this condition is satisfied, it means that the kangaroos will meet at some point in the future, so we return YES
(indicating that the kangaroos will meet):
if (initialDistance % speedDifference === 0) {
return "YES";
}
If this condition is not met, it means that the kangaroos will not meet at any point in the future. Thus, we return NO
:
else {
return "NO";
}
Final resolution
After following the step by step we have our final resolution:
function kagaroo(x1, v1, x2, v2) {
if (v1 > v2) {
const initialDistance = x2 - x1;
const speedDifference = v1 - v2;
if (initialDistance % speedDifference === 0) {
return "YES";
} else {
return "NO";
}
} else {
return "NO";
}
}
Share the code, spread knowledge and build the future! 😉
Images generated by DALL·E 3
Top comments (6)
Interesting problem, thanks for the solution.
Thank you for your contribution Lala 🥰
Very good article, congrats!
Thank you my dear 🥰
Simple and Clear. Good Job !
Thank you very much! 😁