Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Mačky aj myš sa pohybujú rovnakou rýchlosťou skoku (Predpokladajme, že to je 1
na osi x
)
určíme si ako sú od seba vzdalené – (mačka A
, myš), (mačka B
, myš)
kde
,
,
sú pozície na osi
Podľa toho vypíšem odpoveď.
– Ak
-> "Mouse C"
– Ak
-> "Cat A"
– inak -> "Cat B"
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val catsAndMouses: List[(Int, Int, Int)] = lines.tail.map(_.split(" ").map(_.toInt).toList match { case a :: b :: m :: Nil => (a, b, m) case _ => (0, 0, 0) }) catsAndMouses.foreach(cm => { val a = cm._1 val b = cm._2 val m = cm._3 val catACatchMouseSteps = (a - m).abs val catBCatchMouseSteps = (b - m).abs val result = if(catACatchMouseSteps == catBCatchMouseSteps) { "Mouse C" } else if(catACatchMouseSteps < catBCatchMouseSteps) { "Cat A" } else { "Cat B" } println(result) }) } |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.*; public class CatsAndMouse { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { String line = stdin.nextLine(); String[] abmString = line.split(" "); int[] abm = new int[3]; for(int j = 0; j < 3; j++) { abm[j] = Integer.parseInt(abmString[j]); } int a = abm[0]; int b = abm[1]; int m = abm[2]; int catACatchMouseSteps = Math.abs(a - m); int catBCatchMouseSteps = Math.abs(b - m); if(catACatchMouseSteps == catBCatchMouseSteps) { System.out.println("Mouse C"); } else if(catACatchMouseSteps < catBCatchMouseSteps) { System.out.println("Cat A"); } else { System.out.println("Cat B"); } } stdin.close(); } } |
Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
'use strict'; const processData = input => { const lines = input.split('\n'); const abms = lines.slice(1).map(line => line.split(' ').map(i => parseInt(i))); abms.forEach(abm => { const [a, b, m] = abm; const catACatchMouseSteps = Math.abs(a - m); const catBCatchMouseSteps = Math.abs(b - m); if(catACatchMouseSteps == catBCatchMouseSteps) { console.log("Mouse C"); } else if(catACatchMouseSteps < catBCatchMouseSteps) { console.log("Cat A"); } else { console.log("Cat B"); } }); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |