Plus minus hackerrank solution

Problem: Given an array of integers, calculate which fraction of the elements are positive, negative, and zeroes, respectively. Print the decimal value of each fraction.
This problem was asked in Hackerrank. We will see a simple and elegant solution for plus minus problem.

Input Format:
The first line, N, is the size of the array.
The second line contains N space-separated integers describing the array of numbers (A1,A2,A3,,AN).

Output Format:
Print each value on its own line with the fraction of positive numbers first, negative numbers second, and zeroes third.

Sample Input:
6
-4 3 -9 0 4 1

Sample Output:
0.500000
0.333333
0.166667

Explanation
There are 3 positive numbers, 2 negative numbers, and 1 zero in the array.
The fraction of the positive numbers, negative numbers and zeroes are 3/6=0.500000, 2/6=0.333333 and 1/6=0.166667 respectively.

Java program:

We will see a Java program for above plus minus problem.

import java.util.Scanner;

public class FractionCount {

	private static void calculateFraction(int[] arr) {
		int length = arr.length;
		float positiveNumberCount = 0;
		float negativeNumberCount = 0;

		for (int i = 0; i < length; i++) {
			if (arr[i] > 0)
				positiveNumberCount++;
			else if (arr[i] < 0)
				negativeNumberCount++;
		}

		System.out.printf("%.6f\n", positiveNumberCount / length);
		System.out.printf("%.6f\n", negativeNumberCount / length);
		System.out.printf("%.6f",
				(float) (length - (positiveNumberCount + negativeNumberCount))
						/ length);
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int arr[] = new int[n];

		for (int arr_i = 0; arr_i < n; arr_i++) {
			arr[arr_i] = in.nextInt();
		}
		in.close();

		calculateFraction(arr);
	}
}

 

I hope you liked the solution.
Please comment for any questions or doubts.

Leave a Reply