Hackerrank – Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Vypočítame správnu sumu peňazí, ktoré je potrebné zaplatiť – (food_sum - index_of_allergic) / 2
.
Potom stačí porovnať, či sa vypočítaná suma zhoduje s množstom zadaným pri popise problému.
Vytvoril som riešenie v týchto programovacích jazykoch:
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 |
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int k = stdin.nextInt(); int[] prices = new int[n]; for(int i = 0; i < n; i++) { prices[i] = stdin.nextInt(); } int actual = stdin.nextInt(); int charged = (Arrays.stream(prices).sum() - prices[k]) / 2; if(actual == charged) { System.out.println("Bon Appetit"); } else { System.out.println(Math.abs(charged - actual)); } 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 |
'use strict'; const _ = require('lodash'); const processData = input => { const lines = input.split('\n'); const [n, k] = lines[0].split(' '); const items = lines[1].split(' ').map(i => parseInt(i)); const actual = parseInt(lines[2]); const charged = parseInt((_.sum(items) - items[k]) / 2); if(charged === actual) { console.log('Bon Appetit'); } else { console.log(Math.abs(charged - actual)); } }; 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 |
import scala.io.Source object BonAppetit extends App { val lines = Source.stdin.getLines().toList val k = lines.head.split(" ")(1).toInt val items = lines(1).split(" ").map(_.toInt) val actual = lines(2).toInt val charged = (items.sum - items(k)) / 2 println(if(charged == actual) "Bon Appetit" else charged - actual) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
(n, k) = gets.strip.split.map(&:to_i) items = gets.strip.split.map(&:to_i) actual = gets.strip.to_i sum = 0 items.each{ |i| sum += i} charged = (sum - items[k]) / 2 if(charged == actual) puts "Bon Appetit" else puts (actual - charged) end |