Number Line Jumps : Hackerrank
Solution
Problem Statement:
You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity)
- The first kangaroo starts at location
x1
and moves at a rate ofv1
meters per jump - The second kangaroo starts at location
x2
and moves at a rate ofv2
meters per jump
You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES
. Otherwise, return NO
.
For example, kangaroo 1 starts at x1 = 2
with a jump distance of v1 = 1
and kangaroo 2 start at x2= 1
with a jump distance of v2 = 2
. After one jump, they are both at x = 3
, as x1 + v1 = 2+1 = 3, x2 + v2 = 1+2 = 3
, so our answer is YES
Solution:
Consider yourself at origin of that number line, so the whole problem statement will boil down to the below equation. And note that, according to the give problem ,we should understand that time will always be positive and a whole number. In time ‘t’ for them to meet at a point, the below equation should be satisfied.
x1 + v1*t = x2 + v2*t
Solving for t:
t = (x2-x1)/(v1-v2)
For t to be positive whole number :
x2 > x1 and v1 > v2 and (x2-x1)%(v1-v2) == 0
So the final solution will be:
def kangaroo(x1, v1, x2, v2):
if (x2 > x1 and v1 > v2):
if (x2-x1)%(v1-v2) == 0:
return(‘YES’)
else:
return(‘NO’)
else:
return(‘NO’)