Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Skáčem a zničujem energiu po k
pozíciach. Ak sa dostanem na pozíciu 0
, vypíšem zvyšnú energiu.
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 |
import java.util.*; public class JumpingOnTheCloudsRevisited { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int k = stdin.nextInt(); int[] clouds = new int[n]; for(int i = 0; i < n; i++) { clouds[i] = stdin.nextInt(); } int energy = 100; int pos = k % n; energy -= ((clouds[pos] == 1) ? 3 : 1); while(pos != 0) { pos = (pos + k) % n; energy -= ((clouds[pos] == 1) ? 3 : 1); } System.out.println(energy); 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 |
'use strict'; const processData = input => { const lines = input.split('\n'); const [n, k] = lines[0].split(' ').map(i => parseInt(i)); const clouds = lines[1].split(' ').map(i => parseInt(i)); let energy = 100; let pos = k % n; energy -= ((clouds[pos] == 1) ? 3 : 1); while(pos != 0) { pos = (pos + k) % n; energy -= ((clouds[pos] == 1) ? 3 : 1); } console.log(energy); }; 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 |
object JumpingOnTheCloudsRevisited extends App { val lines = Source.stdin.getLines().toList val nk = lines.head.split(" ").map(_.toInt) val n = nk(0) val k = nk(1) val clouds = lines(1).split(" ").map(_.toInt) var energy = 100 var pos = k % n energy -= (if(clouds(pos) == 1) 3 else 1) while(pos != 0) { pos = (pos + k) % n energy -= (if(clouds(pos) == 1) 3 else 1) } println(energy) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
(n, k) = gets.split(" ").map(&:to_i) clouds = gets.split(" ").map(&:to_i) energy = 100 pos = k % n energy -= ((clouds[pos] == 1) ? 3 : 1) while(pos != 0) do pos = (pos + k) % n energy -= ((clouds[pos] == 1) ? 3 : 1) end puts energy |