Problem Statement
A description of the problem can be found on Hackerrank.
Solution
sum = (b - a + 1) * no_candies
for each operations. Average and floor the sum
.
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 |
import java.math.BigInteger; import java.util.*; import java.math.BigInteger; public class FillingJars { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int jars = stdin.nextInt(); int operations = stdin.nextInt(); BigInteger sum = BigInteger.ZERO; for(int i = 0; i < operations; i++) { BigInteger a = BigInteger.valueOf(stdin.nextLong()); BigInteger b = BigInteger.valueOf(stdin.nextLong()); BigInteger candies = BigInteger.valueOf(stdin.nextLong()); sum = sum.add((b.subtract(a).add(BigInteger.ONE)).multiply(candies)); } BigInteger avg = sum.divide(BigInteger.valueOf(jars)); System.out.println(avg); 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 |
function processData(input) { var lines = input.split("\n"); var head = lines[0].split(" ").map(i => parseInt(i)); var jars = head[0]; var operations = head[1]; var sum = 0; for(var i = 1; i < lines.length; i++) { var nums = lines[i].split(" ").map(i => parseInt(i)); var a = nums[0]; var b = nums[1]; var candies = nums[2]; sum += (b - a + 1) * candies; } var avg = sum / jars; console.log(parseInt(Math.floor(avg))); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import scala.io.Source object Solution extends App { val lines = Source.stdin.getLines().toList val jars = lines.head.split(" ").map(_.toInt).toList(0) val operations = lines.head.split(" ").map(_.toInt).toList(1) val description = lines.tail var sum = 0L description.foreach { line => { val ints = line.split(" ").map(_.toLong) val a = ints(0) val b = ints(1) val candies = ints(2) sum += ((b - a + 1) * candies) } } val avg = sum / jars println(avg) } |
Ruby
1 2 3 4 5 6 7 8 9 |
(n_jars, operations) = gets.chomp.split.map { |i| i.to_i} sum = 0 operations.times do (a, b, candies) = gets.chomp.split.map { |i| i.to_i} sum += ((b - a + 1) * candies) end average = sum.to_f / n_jars answer = average.floor puts answer |