Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Create index pairs variations for all indexes that pair is unique – it means when (i, j)
exists (j, i)
is the same. For each pair calculate the sum of values at corresponding index. If is divisible, count them and print
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 |
import java.util.*; public class DivisibleSumPairs { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int divisor = stdin.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = stdin.nextInt(); } int count = 0; for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { if((array[i] + array[j]) % divisor == 0) { count++; } } } System.out.println(count); 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 line1 = lines[0]; const divisor = parseInt(line1.split(' ')[1]); const array = lines[1].split(' ').map(item => parseInt(item)); let count = 0; for(let i = 0; i < array.length - 1; i++) { for(let j = i + 1; j < array.length; j++) { if((array[i] + array[j]) % divisor === 0) { count++; } } } console.log(count); }; 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 |
object DivisibleSumPairs extends App { val lines = Source.stdin.getLines().toList val divisor = lines(0).split(" ").map(_.toInt).toList(1) val array = lines(1).split(" ").map(_.toInt) val indexPairs = array.indices.flatMap(i => array.indices.slice(i + 1, array.length).map(j => (i, j))) val divisible = indexPairs.count(pair => (array(pair._1) + array(pair._2)) % divisor == 0) println(divisible) } |
Ruby
1 2 3 4 5 6 7 8 9 10 |
(n, divisor) = gets.split(" ").map {|i| i.to_i} array = gets.split(" ").map {|i| i.to_i} count = 0 for a in 0..(n-2) do for j in (a+1)..(n-1) do count += 1 if ((array[a] + array[j]) % divisor == 0) end end puts count |