Plus Minus | Hacker Rank

Problem:

Given an array of integers, calculate the ratios of its elements that are positivenegative, and zero. Print the decimal value of each fraction on a new line with  places after the decimal.

Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to  are acceptable.

Example

There are  elements, two positive, two negative and one zero. Their ratios are  and . Results are printed as:

0.400000
0.400000
0.200000
Solution:

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the plusMinus function below.
    static void plusMinus(int[] arr) {
float fp=0;float fn=0;float fo=0;
int l=arr.length;
for(int i=0;i<l;i++){
if(arr[i]>0)
{
    fp++;
}
else if (arr[i]<0)
{
    fn++;
}
else{
    fo++;
}
}

float op=fp/l;
float on=fn/l;
float oo=fo/l;
System.out.println(op);
System.out.println(on);
System.out.println(oo);

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] arr = new int[n];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        plusMinus(arr);

        scanner.close();
    }
}

Comments

Popular posts from this blog

Write a Function | Hacker Rank Solution in Python

Diagonal Difference | Hacker Rank Solution in C

Print Function | Hacker Rank Solution in Python