Hackerrank – Ice Cream Parlor
Popis problému Celý popis zadania sa nacháza – Hackerrank. Riešenie Pre každú i-tú cenovku zisti, či súčet i-tej a (i+1)-ej ceny je rovný požadovanej sume. Vytvoril som riešenie v týchto programovacích jazykoch: Java JavaScript Scala 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 26 |
import java.util.*; public class IceCreamParlor { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { int amount = Integer.parseInt(stdin.nextLine()); int length = Integer.parseInt(stdin.nextLine()); int[] costs = new int[length]; String[] strings = stdin.nextLine().split(" "); for(int j = 0; j < length; j++) { costs[j] = Integer.parseInt(strings[j]); } for(int j = 0; j < length - 1; j++) { for(int k = j + 1; k < length; k++) { if(costs[j] + costs[k] == amount) { System.out.println((j + 1) + " " + (k + 1)); } } } } 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 27 28 29 |
'use strict'; const processData = input => { let lines = input.split('\n'); let tests = parseInt(lines[0]); let index = 1; for(let i = 0; i < tests; i++) { let amount = parseInt(lines[index++]); let lenght = parseInt(lines[index++]); let costs = lines[index++].split(" ").map(i => parseInt(i)); let indexes = []; for(let j = 0; j < lenght - 1; j++) { for(let k = j + 1; k < lenght; k++) { if(costs[j] + costs[k] === amount) { indexes.push(j + 1); indexes.push(k + 1); } } } console.log(indexes.join(" ")); } }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _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 20 21 22 23 24 25 26 |
import scala.collection.mutable.ListBuffer import scala.io.Source object IceCreamParlor extends App { val console = Source.stdin.bufferedReader() val tests = console.readLine().toInt (0 until tests).foreach(_ => { val amount = console.readLine().toInt val lenght = console.readLine().toInt val costs = console.readLine().split(" ").map(_.toInt) println(indexes(costs, amount).mkString(" ")) }) def indexes(costs: Array[Int], amount: Int): List[Int] = { val result: ListBuffer[Int] = ListBuffer.empty (0 until costs.length - 1).foreach(i => { (i + 1 until costs.length).foreach(j => { if(costs(i) + costs(j) == amount) { result += i + 1 result += j + 1 } }) }) result.toList } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 |
tests = gets.chomp.to_i tests.times do m = gets.chomp.to_i n = gets.chomp.to_i flavors = gets.chomp.split.map { |e| e.to_i } for i in 0...flavors.length - 1 do for j in i + 1...flavors.length do puts "#{i + 1} #{j + 1}" if flavors[i] + flavors[j] == m end end end |