Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I jumped for k
positions and lowered the energy. If I reached position 0
I printed the remaining enenergy.
I created solution in:
All solutions are also available on my GitHub.
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 |