Hackerrank – Popis problému Celý popis zadania sa nacháza – Hackerrank. Riešenie Urobíme si všetky dvojice pozícii ale len také, ktorých hodnoty sú rovnaké. Najdeme najväčší rozdiel medzi pozíciami. Vytvoril som riešenie v týchto programovacích jazykoch: Scala Java JavaScript Ruby Všetky riešenia sú dostupné aj na mojom GitHub profile. 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 MinimumDistances { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = stdin.nextInt(); } int min = Integer.MAX_VALUE; for(int i = 0; i < n - 1; i++) { for(int j = i + 1; j < n; j++) { if(array[i] == array[j]) { min = Math.min(min, Math.abs(j - i)); } } } int result = (min == Integer.MAX_VALUE ? -1 : min); 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
|
'use strict'; const processData = input => { const lines = input.split('\n'); const array = lines[1].split(' ').map(i => parseInt(i)); let min = 999999999; for(let i = 0; i < array.length - 1; i++) { for(let j = i + 1; j < array.length; j++) { if(array[i] == array[j]) { min = Math.min(min, Math.abs(j - i)); } } } const result = (min === 999999999 ? -1 : min); 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)); |
Scala
|
object MinimumDistances extends App { val lines = Source.stdin.getLines().toList 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 equalValues = indexPairs.filter(pair => array(pair._1) == array(pair._2)) val distances = equalValues.map(pair => (pair._1 - pair._2).abs) val result = if(distances.isEmpty) -1 else distances.min println(result) } |
[…]