Hackerrank – Problem Statement A description of the problem can be found on Hackerrank. Solution Look at the implementation. The steps are in problem description. I created solution in: Scala Java Javascript All solutions are also available on my GitHub profile. Scala
|
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val bars = lines(1).split(" ").map(_.toInt).toList val dm = lines(2).split(" ").map(_.toInt).toList match { case i :: j :: Nil => (i, j) } val allConsecutives = bars.sliding(dm._2) val result = allConsecutives.count(bars => bars.sum == dm._1) 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
|
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); int[] bars = new int[tests]; for(int i = 0; i < tests; i++) { bars[i] = stdin.nextInt(); } int d = stdin.nextInt(); int m = stdin.nextInt(); int result = 0; for(int i = 0; i < bars.length - m + 1; i++) { int sum = 0; for(int j = i; j < i + m; j++) { sum += bars[j]; } if(sum == d) { result++; } } System.out.println(result); 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
|
'use strict'; const processData = input => { const lines = input.split('\n'); const bars = lines[1].split(' ').map(i => parseInt(i)); const [d, m] = lines[2].split(' ').map(i => parseInt(i)); let result = 0; for(let i = 0; i < bars.length - m + 1; i++) { let sum = 0; for(let j = i; j < i + m; j++) { sum += bars[j]; } if(sum == d) { result++; } } console.log(result); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |