Hackerrank – Halloween Party
Problem Statement A description of the problem can be found on Hackerrank. Solution Calculate chocolate pieces as: I created solution in: Java JavaScript Scala Ruby 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 |
import java.util.*; public class HalloweenParty { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); for(int i = 0; i < tests; i++) { long k = stdin.nextLong(); long horizontal = k / 2; long vertical = k - horizontal; System.out.println(vertical * horizontal); } stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
'use strict'; const processData = input => { let lines = input.split("\n"); let slices = lines.map(i => parseInt(i)); const pieces = k => { let horizontal = parseInt(k / 2); let vertical = k - horizontal; return vertical * horizontal; }; for(let i = 1; i < slices.length; i++) { console.log(pieces(slices[i])); } }; 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 |
import scala.io.Source object HalloweenParty extends App { val lines = Source.stdin.getLines() val slices = lines.drop(1).map(_.toLong) val result = slices.map(pieces) println(result.mkString("\n")) def pieces(k: Long): Long = { val horizontal = k / 2 val vertical = k - horizontal vertical * horizontal } } |
Ruby
1 2 3 4 5 6 7 |
test_cases = gets.chomp.to_i test_cases.times do |test| slices = gets.chomp.to_i horizontal_slices = slices / 2 vertical_slices = slices - horizontal_slices puts vertical_slices * horizontal_slices end |