08
Jan
2020

Hackerrank Kangaroo (C++)

C++ :

string kangaroo(int x1, int v1, int x2, int v2) {
    string yesNo = "NO";
    int jumps = 100000, jumpNo = 1;

    while(jumpNo < jumps){
        if((x1 + (jumpNo * v1)) == (x2 + (jumpNo * v2))){
            yesNo = "YES";
            break;
        }
        jumpNo++;
    }

    return yesNo;
}

Explanation:

Make jumps (the number of max times the kangaroos can jump) an arbitrarily large number (such as 100,000 as above), then in the while loop, check if starting distance of kangaroo 1 (x1) + total distance jumped (jumpNo * jumpingDistance v1) is the same as the starting distance of kangaroo 2 (x2) + total distance jumped (jumpNo * jumpingDistance v2).

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *