Cats and a Mouse - HackerRank Solution | Using C/C++ | Code4xU

 

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  queries in the form of , and  representing the respective positions for cats  and , and for mouse . Complete the function  to return the appropriate answer to each query, which will be printed on a new line.

  • If cat  catches the mouse first, print Cat A.
  • If cat  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



The cats are at positions  (Cat A) and  (Cat B), and the mouse is at position . Cat B, at position  will arrive first since it is only  unit away while the other is  units away. Return 'Cat B'.

Function Description

Complete the catAndMouse function in the editor below.

catAndMouse has the following parameter(s):

  • int x: Cat 's position
  • int y: Cat 's position
  • int z: Mouse 's position.

Returns

  • string: Either 'Cat A', 'Cat B', or 'Mouse C'

Input Format

The first line contains a single integer, , denoting the number of queries.
Each of the  subsequent lines contains three space-separated integers describing the respective values of  (cat 's location),  (cat 's location), and  (mouse 's location).

Constraints

Sample Input 0

1 2 3
1 3 2

Sample Output 0

Cat B
Mouse C

Solution:

Code in C++:


#include<iostream> #include<cstdlib> using namespace std; int main(){ int q; cin>>q; while(q--) { int x,y,z; cin>>x>>y>>z; x=abs(x-z); y=abs(y-z); if(x==y) cout<<"Mouse C"<<endl; else if(x<y) cout<<"Cat A"<<endl; else { cout<<"Cat B"<<endl; } } return 0; }

 Code in C:

#include<stdio.h> typedef unsigned u; int main() { u t,a,b,c; for(scanf("%u",&t);t--;) { scanf("%u%u%u",&a,&b,&c); a=c>a?c-a:a-c; b=c>b?c-b:b-c; printf(a>=b?a==b?"Mouse C\n":"Cat B\n":"Cat A\n"); } return 0; }
Sajal Gupta

Hi, i am sajal.I am a hardworking engineering graduate specialised in Computer Science Engineering ... Along with my degree, I completed C/C++,.Net,Java and SQL courses From Youtube and Other sources and various technologies.I learnt helped me develop my final year project called Code4xU..

Post a Comment