Number Line Jumps

Klecianny Melo - Apr 11 - - Dev Community

Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Number line jumps.

The problem

Image description

Image description

The solution

Image description

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) {}
Enter fullscreen mode Exit fullscreen mode

Let's start by checking whether the first kangaroo has a greater speed than the second kangaroo:

if (v1 > v2) {}
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Now let's calculate the speed difference, in the constant speedDifference. To do this, let's subtract v1 from v2:

const speedDifference = v1 - v2;
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

Final resolution

Image description

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";
    }
}
Enter fullscreen mode Exit fullscreen mode

Share the code, spread knowledge and build the future! 😉

Images generated by DALL·E 3

. . . . . . . . . . . . . . . . . . . . . . . .