Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I created a pointer for an actual position which starts at index 0
.
I always tried to jump at position i + 2
. If it is not possible because of thundercloud I step at i + 1
position. I do it until the pointer is at last cloud.
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 24 25 26 27 |
import java.util.*; public class JumpingOnTheClouds { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = Integer.parseInt(stdin.nextLine()); String[] numbers = stdin.nextLine().split(" "); int[] clouds = new int[n]; for(int i = 0; i < n; i++) { clouds[i] = Integer.parseInt(numbers[i]); } int steps = 0; int index = 0; while (index < clouds.length - 1) { if((index + 2 < clouds.length) && clouds[index + 2] != 1) { index = index + 2; } else { index = index + 1; } steps += 1; } System.out.println(steps); 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 |
'use strict'; const processData = input => { const lines = input.split('\n'); const clouds = lines[1].split(' ').map(i => parseInt(i)); let steps = 0; let index = 0; while (index < clouds.length - 1) { if((index + 2 < clouds.length) && clouds[index + 2] != 1) { index = index + 2; } else { index = index + 1; } steps += 1; } console.log(steps); }; 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 |
import scala.io.Source object JumpingOnTheClouds extends App { val lines = Source.stdin.getLines().toList val clouds = lines(1).split(" ").map(_.toInt) var steps = 0 var index = 0 while (index < clouds.length - 1) { if((index + 2 < clouds.length) && clouds(index + 2) != 1) { index = index + 2 } else { index = index + 1 } steps += 1 } println(steps) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
n = gets.to_i clouds = gets.split(" ").map{|i| i.to_i} steps = 0 index = 0 while (index < clouds.length - 1) do if((index + 2 < clouds.length) && clouds[index + 2] != 1) index = index + 2 else index = index + 1 end steps += 1 end puts steps |