Hackerrank – Flowers
Popis problému Celý popis zadania sa nacháza – Hackerrank. Riešenie Usporiadaj všetky ceny zostupne. Rovnica pre určenie ceny kvetu i: $$total = \sum_{i=0}^{n-1}((i / k + 1) * price_{i})$$ Vytvoril som riešenie v týchto programovacích jazykoch: Java JavaScript Ruby Scala 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 27 28 29 |
import java.util.*; public class Flowers { private static class Descending implements Comparator<Integer> { @Override public int compare(Integer i, Integer j) { return j - i; } } public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = stdin.nextInt(); int k = stdin.nextInt(); Integer[] prices = new Integer[n]; for(int i = 0; i < n; i++) { prices[i] = stdin.nextInt(); } Arrays.sort(prices, new Descending()); int sum = 0; for(int i = 0; i < n; i++) { int factor = i / k; sum += prices[i] * (factor + 1); } System.out.println(sum); 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 => { let lines = input.split('\n'); let definition = lines[0].split(' ').map(i => parseInt(i)); let n = definition[0]; let k = definition[1]; let prices = lines[1].split(" ").map(i => parseInt(i)); let descendingPrices = prices.sort((i, j) => j - i); let totalPrice = 0; for(let i = 0; i < n; i++) { let factor = parseInt(i / k); totalPrice += (factor + 1) * descendingPrices[i]; } console.log(totalPrice); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Ruby
1 2 3 4 5 6 7 8 9 10 |
(n, k) = gets.chomp.split.map { |e| e.to_i } prices = gets.chomp.split.map { |e| e.to_i } prices.sort! { |i,j| j <=> i } result = 0 n.times do |i| factor = i / k result += (factor + 1) * prices[i] end puts result |