Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Je potrebné skontrolovať tieto 2 prípady:
- Ak je menšie ako výsledok je
"NO"
. To znamená, že kengura 1 nikdy nedostihne kenguru 2. - Vypočítal som rozdiel medzi počiatočnými pozíciami a rozdiel medzi veľkosťami ich skokov . Ak , potom kengura 1 bude schopná dostihnúť kenguru2. Inak vypíš
"NO"
.
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
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 |
import java.util.*; public class Kangaroo { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int x1 = stdin.nextInt(); int v1 = stdin.nextInt(); int x2 = stdin.nextInt(); int v2 = stdin.nextInt(); System.out.println(isSameLocation(x1, v1, x2, v2)); stdin.close(); } private static String isSameLocation(int x1, int v1, int x2, int v2) { if(v1 < v2) return "NO"; if(x1 < x2 && v1 > v2) { int xDiff = Math.abs(x1 - x2); int vDiff = Math.abs(v1 - v2); if(xDiff % vDiff == 0) { return "YES"; } else { return "NO"; } } return "NO"; } } |
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 28 |
'use strict'; const processData = input => { const lines = input.split('\n'); const [x1, v1, x2, v2] = lines[0].split(' ').map(i => parseInt(i)); console.log(sameLocation(x1, v1, x2, v2)); }; const sameLocation = (x1, v1, x2, v2) => { if(v1 < v2) return "NO"; if(x1 < x2 && v1 > v2) { const xDiff = Math.abs(x1 - x2); const vDiff = Math.abs(v1 - v2); if(xDiff % vDiff == 0) { return "YES"; } else { return "NO"; } } return "NO"; }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
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 |
object Kangaroo extends App { val lines = Source.stdin.getLines().toList val numbers = lines.head.split(" ").map(_.toInt) val kangaroo1 = (numbers(0), numbers(1)) val kangaroo2 = (numbers(2), numbers(3)) println(if(sameLocation(kangaroo1, kangaroo2)) "YES" else "NO") def sameLocation(k1: (Int, Int), k2: (Int, Int)): Boolean = { val x1 = k1._1 val x2 = k2._1 val v1 = k1._2 val v2 = k2._2 if(v1 < v2) return false if(x1 < x2 && v1 > v2) { val xDiff = (x1 - x2).abs val vDiff = (v1 - v2).abs if(xDiff % vDiff == 0) { return true } else { return false } } false } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def same_location(x1, v1, x2, v2) return "NO" if(v1 < v2) if(x1 < x2 && v1 > v2) xDiff = (x1 - x2).abs vDiff = (v1 - v2).abs if(xDiff % vDiff == 0) return "YES" else return "NO" end end "NO" end (x1, v1, x2, v2) = gets.strip.split(" ").map {|i| i.to_i} puts same_location(x1, v1, x2, v2) |