I got back to Hackerrank after quite a while and they got some new exercises so I decided to start clearing them from my desk.

###### Exercise Description

There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location X1 and moves at a rate of V1 meters per jump. The second kangaroo starts at location X2 and moves at a rate of V2 meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they’ll ever land at the same location at the same time?

###### What I have done

This task is quite simple to solve but as I noticed a lot of developers solved it with a huge loop ~999999

and in the bottom line this approach solves the exercise, but this surely not the right solution for the long term as it will not solve the problem in big numbers and it surely is a waste of space and power.

If you write down your exercise on paper and try to think about it a bit before you start coding you will find a much better solution.

** You can read the exercise details in the bottom of the page.

###### Solution

After you think about this question you get to under stand that you need to find the breakpoint of those 2 kangaroos.

```
X1 + V1*T = X2 + V2*T
```

so after you do some simple math you get to this quotation:

```
T = (X1 - X2) / (V2 - V1)
```

so we have all the X1, V1, X2, V2 variables, so we have the T solution.

Now if T is negative the kangaroos will never meet, if T is not an integer so they will not meet as well.

The only way the kangaroos will meet is when T is and unsigned integer.

```
function doTheyMeet(x1, v1, x2, v2) {
var res = (x1-x2)/(v2-v1);
if ( ! Number.isInteger(res))
return false;
if (res < 0)
return false;
return true;
}
```

## Leave a Reply