13
Jan
2020

Hackerrank Cats and a Mouse (C++)

C++ :

string catAndMouse(int x, int y, int z) {
    string result = "";
    bool meet = false;

    if(x == z || y == z || x == y){
        meet = true;
    }

    while(!meet){
        //cat a moves left
        if(x > z){
            x--;
        }else{
            x++;
        }

        //cat b moves left
        if(y > z){
            y--;
        }else{
            y++;
        }

        if(x == z || y == z || x == y){
            meet = true;
        }

    }

    if(meet){
        if(x == y){
            result = "Mouse C";
        }else if(y == z){
            result = "Cat B";
        }else{
            result = "Cat A";
        }
    }

    return result;
}

Explanation:

This one is cute. Reminds me of Tom and Jerry, or in this case Toms and Jerry.

First, check if either Tom A, Tom B, or Jerry has met. Either of them would do. If yes, set meet = True, and we don’t even have to enter the moving game.

Otherwise, the while loop will run until the either Toms meet, or when either Tom catches Jerry. But first we need to determine the direction which both Toms move. If Tom is larger than Jerry, which means that Tom is on the right of Jerry, Tom moves left (-1), otherwise, Tom moves right (+1).

Then we check if either of the Toms meet Jerry, or all 3 of them meet at the same time. If yes, meet is set to true, and exit the while loop.

In the final if, we check what actually happened. If all 3 of them meet at the same time, Tom A and Tom B fight, Jerry runs. It is important to check for this condition first, since both Toms reach Jerry at the same time, causing x == y ( == z), since the other two cases are where only one Tom reaches Jerry (x == z) or (y == z).

You may also like...

Leave a Reply

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