Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
I checked each consequent combination of (i, j, k)
, if it is valid according to condition.
There is a catch. I had to stop an iteration if array[j] - array[i] <= d
or array[k] - array[j] <= d
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 |
object BeautifulTriplets extends App { val lines = Source.stdin.getLines().toList val d = lines(0).split(" ").map(_.toInt).toList(1) val array = lines(1).split(" ").map(_.toInt) val indices = array.indices var beautifulTriplets = 0 for(i <- (0 until indices.length - 2)) { for (j <- ((i + 1) until indices.length - 1) if (array(j) - array(i) <= d)) { for (k <- ((j + 1) until indices.length) if (array(k) - array(j) <= d)) { if (((array(j) - array(i)) == d) && ((array(k) - array(j)) == d)) { beautifulTriplets += 1 } } } } println(beautifulTriplets) } |
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 [n, d] = lines[0].split(' ').map(i => parseInt(i)); const array = lines[1].split(' ').map(i => parseInt(i)); let triplets = 0; for(let i = 0; i < n - 2; i++) { for(let j = i + 1; j < n - 1; j++) { if(array[j] - array[i] > d) break; for(let k = j + 1; k < n; k++) { if(array[k] - array[j] > d) break; if((array[k] - array[j] == d) && (array[j] - array[i] == d)) { triplets++; } } } } console.log(triplets); }; 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 |
object BeautifulTriplets extends App { val lines = Source.stdin.getLines().toList val d = lines(0).split(" ").map(_.toInt).toList(1) val array = lines(1).split(" ").map(_.toInt) val indices = array.indices var beautifulTriplets = 0 for(i <- (0 until indices.length - 2)) { for (j <- ((i + 1) until indices.length - 1) if (array(j) - array(i) <= d)) { for (k <- ((j + 1) until indices.length) if (array(k) - array(j) <= d)) { if (((array(j) - array(i)) == d) && ((array(k) - array(j)) == d)) { beautifulTriplets += 1 } } } } println(beautifulTriplets) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
(n, d) = gets.strip.split(" ").map {|i| i.to_i} array = gets.strip.split(" ").map {|i| i.to_i} triplets = 0 for i in 0...(n-2) for j in (i+1)...(n-1) break if (array[j] - array[i] > d) for k in (j+1)...(n) break if (array[k] - array[j] > d) triplets += 1 if((array[k] - array[j] == d) && (array[j] - array[i] == d)) end end end puts triplets |