Kangaroo Hackerrank Problem coderinme

Kangaroo

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?

Input Format

A single line of four space-separated integers denoting the respective values of x1, v1, x2, and v2.
Kangaro
Output Format

Print YES if they can land on the same location at the same time; otherwise, print NO.

Note: The two kangaroos must land at the same location after making the same number of jumps.

Sample Input 0

0 3 4 2
Sample Output 0

YES
Explanation 0
0->3->6->9->12
4->6->8->10->12

The two kangaroos jump through the following sequence of locations:

Thus, the kangaroos meet after jumps and we print YES.

Sample Input 1

0 2 5 3
Sample Output 1

NO
Explanation 1

The second kangaroo has a starting location that is ahead (further to the right) of the first kangaroo’s starting location (i.e.,x2>x1 ). Because the second kangaroo moves at a faster rate (meaning v2>v1) and is already ahead of the first kangaroo, the first kangaroo will never be able to catch up. Thus, we print NO.

I Method

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int x1,v1,x2,v2;
    cin>>x1>>v1>>x2>>v2;
     if(v2>v1 || v2==v1){
            cout<<"NO";
        }else{
            if((x2-x1)%(v1-v2)==0){
                 cout<<"YES";
            }else{
                  cout<<"NO";
            }
            
        }
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    return 0;
}

II Method

x1, v1, x2, v2 = map(int, raw_input().split())
X = [x1, v1]
Y = [x2, v2]
back = min(X, Y)
fwd = max(X, Y)
dist = fwd[0] - back[0]

while back[0] < fwd[0]:
    back[0] += back[1]
    fwd[0] += fwd[1]
    if fwd[0] - back[0] >= dist:
        break

print ["NO", "YES"][back[0] == fwd[0]]

Kangaroo
kangaroo

A web developer(Front end and Back end), and DBA at csdamu.com. Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me @about.me/s.saifi

One comment: On Kangaroo Hackerrank Problem coderinme

  • if(x1==x2)
    return “YES”;
    else if(x2>x1&&v2>=v1)
    return “NO”;
    else if(x2<x1&&v2<=v1)
    return "NO";
    else
    {
    auto n=(double)(x2-x1)/(v1-v2);
    auto nt =(x2-x1)/(v1-v2);
    if(n==double(nt))
    return "YES";
    else
    return "NO";
    }

Leave a reply:

Your email address will not be published.