HackerRank Cats and a Mouse Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Cats and a Mouse Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Cats and a Mouse Solution
HackerRank Cats and a Mouse Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Cats and a Mouse Solution

Task

Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse does not move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight.

You are given q queries in the form of x, y, and z representing the respective positions for cats A and B, and for mouse C. Complete the function catAndMouse to return the appropriate answer to each query, which will be printed on a new line.

  • If cat A catches the mouse first, print Cat A.
  • If cat B catches the mouse first, print Cat B.
  • If both cats reach the mouse at the same time, print Mouse C as the two cats fight and mouse escapes.

Example

x =2
y = 5
z = 4
The cats are at positions 2 (Cat A) and 5 (Cat B), and the mouse is at position 4. Cat B, at position 5 will arrive first since it is only 1 unit away while the other is 2 units away. Return ‘Cat B’.

Function Description

Complete the catAndMouse function in the editor below.

catAndMouse has the following parameter(s):

  • int x: Cat A’s position
  • int y: Cat B’s position
  • int z: Mouse C’s position

Returns

  • string: Either ‘Cat A’, ‘Cat B, or ‘Mouse C’

Input Format

The first line contains a single integer, q, denoting the number of queries.
Each of the q subsequent lines contains three space-separated integers describing the respective values of x (cat A‘s location), y (cat Bs location), and z (mouse C‘s location).

Constraints

  • 1 <= q <= 100
  • 1 <= xyz <= 100

Sample Input 0

2
1 2 3
1 3 2

Sample Output 0

Cat B
Mouse C

Explanation 0

Query 0: The positions of the cats and mouse are shown below: image

Cat B will catch the mouse first, so we print Cat B on a new line.

Query 1: In this query, cats A and B reach mouse C at the exact same time: image

Because the mouse escapes, we print Mouse C on a new line.

HackerRank Cats and a Mouse Solution

Cats and a Mouse Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
    int q; 
    scanf("%d",&q);
    for(int a0 = 0; a0 < q; a0++){
        int x; 
        int y; 
        int z; 
        scanf("%d %d %d",&x,&y,&z);
        int a = abs(x - z);
        int b = abs(y - z);
        if (a < b) printf("Cat A\n");
        else if (b < a) printf("Cat B\n");
        else printf("Mouse C\n");
    }
    return 0;
}

Cats and a Mouse Solution in Cpp

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
    int q;
    cin >> q;
    for(int a0 = 0; a0 < q; a0++){
        int x;
        int y;
        int z;
        cin >> x >> y >> z;
        int d1 = abs(x - z), d2 = abs(y - z);
        if (d1 < d2) cout << "Cat A" << endl;
        else if (d1 > d2) cout << "Cat B" << endl;
            else cout << "Mouse C" << endl;
    }
    return 0;
}

Cats and a Mouse Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int x = in.nextInt();
            int y = in.nextInt();
            int z = in.nextInt();
            int a = Math.abs(x-z);
            int b = Math.abs(y-z);
            if (a==b)
                System.out.println("Mouse C");
            if (a<b)
                System.out.println("Cat A");
            if (a>b)
                System.out.println("Cat B");
        }
    }
}

Cats and a Mouse Solution in Python

#!/bin/python
import sys
q = int(raw_input().strip())
for a0 in xrange(q):
    x,y,z = raw_input().strip().split(' ')
    x,y,z = [int(x),int(y),int(z)]
    if abs(x-z) == abs(y-z):
        print 'Mouse C'
    elif abs(x-z)<abs(y-z):
        print 'Cat A'
    else:
        print 'Cat B'

Cats and a Mouse Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
    input_stdin += data;
});
process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});
function readLine() {
    return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
    var q = parseInt(readLine());
    for(var a0 = 0; a0 < q; a0++){
        var x_temp = readLine().split(' ');
        var x = parseInt(x_temp[0]);
        var y = parseInt(x_temp[1]);
        var z = parseInt(x_temp[2]);
        
        var a = Math.abs(x - z);
        var b = Math.abs(y - z);
        if(a > b) {
            console.log('Cat B');
        }
        else if (a === b) {
            console.log('Mouse C');
        }
        else {
            console.log('Cat A');
        }
    }
}

Cats and a Mouse Solution in Scala

object Solution extends App {
  import io.StdIn._
    
  val q = readLine.trim.toInt
  for(_ <- 1 to q) {
    val Array(a,b,c) = readLine.trim.split(" +").map(_.toInt)
    if((a-c).abs < (b-c).abs) println("Cat A")
    else if((a-c).abs > (b-c).abs) println("Cat B")
    else println("Mouse C")
  }
}

Cats and a Mouse Solution in Pascal

(* Enter your code here. Read input from STDIN. Print output to STDOUT *)
uses math;
var i,j,n,z,x,y:longint;
 begin
 read(n);
 for i:=1 to n do
   begin
   read(x,y,z);
   if abs(x-z)>abs(y-z)  then writeln('Cat B') else
   if abs(x-z)<abs(y-z)   then writeln('Cat A') else
   writeln('Mouse C');
 end;
end.

Disclaimer: This problem (Cats and a Mouse) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Forming a Magic Square Solution

Leave a Reply

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