Problem Statement
A description of the problem can be found on Hackerrank.
Solution
After reading all numbers in array, you have to filter this array according to three conditions – number greater than zero, lower then zero and equals to zero. Count the subarrays and divide by array length.
I created solution in 4 languages:
All solutions are also available on my GitHub.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.Locale object PlusMinus extends App { val console = io.Source.stdin.bufferedReader() val n = console.readLine().toInt val arr = console.readLine().split(" ").map(_.toInt) println("%.3f".formatLocal(Locale.ENGLISH, arr.count(_ > 0) / n.toDouble)) println("%.3f".formatLocal(Locale.ENGLISH, arr.count(_ < 0) / n.toDouble)) println("%.3f".formatLocal(Locale.ENGLISH, arr.count(_ == 0) / n.toDouble)) } |
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 30 31 32 |
import java.util.*; public class PlusMinus { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int n = Integer.parseInt(stdin.nextLine()); String[] numbers = stdin.nextLine().split(" "); int positives = 0; int negatives = 0; int zeroes = 0; for(int i = 0; i < n; i++) { int num = Integer.parseInt(numbers[i]); if(num > 0) { positives++; } else if(num < 0) { negatives++; } else { zeroes++; } } System.out.println(String.format(Locale.ENGLISH, "%.3f", (double) positives / n)); System.out.println(String.format(Locale.ENGLISH, "%.3f", (double) negatives / n)); System.out.println(String.format(Locale.ENGLISH, "%.3f", (double) zeroes / n)); 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 30 31 32 33 34 35 36 37 38 39 |
function processData(input) { var lines = input.split(" "); var n = parseInt(lines[0]); var arr = lines[1].split(" ").map(function(s) {return parseInt(s);}); var positives = 0; var negatives = 0; var zeroes = 0; for(var i = 0; i < arr.length; i++) { if(arr[i] > 0) { positives++; } else if(arr[i] < 0) { negatives++; } else { zeroes++; } } console.log(positives / n); console.log(negatives / n); console.log(zeroes / n); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
n = gets.to_s.to_i arr = gets.to_s.split(" ").map { |s| s.to_i } positives = 0 negatives = 0 zeroes = 0 for i in arr do positives += 1 if i > 0 negatives += 1 if i < 0 zeroes += 1 if i == 0 end puts positives / n.to_f puts negatives / n.to_f puts zeroes / n.to_f |