Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Plus Minus Problem Solution

Yashwant Parihar, April 10, 2023April 10, 2023

In this post, We are going to solve HackerRank Plus Minus Problem. Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal.

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

Example

arr = [ 1, 1, 0, -1, -1]

There are n = 5 elements, two positive, two negatives, and one zero. Their ratios are 2/5 = 0.4000000, 2/5 = 0.4000000, and 1/5 = 0.2000000. Results are printed as:

0.400000
0.400000
0.200000

Function Description

Complete the plus-minus function in the editor below.

plus-minus has the following parameter(s):

  • int arr[n]: an array of integers

Print
Print the ratios of positive, negative,
and zero values in the array. Each value should be printed on a separate line with 6 digits after the decimal. The function should not return a value.

Input Format

The first line contains an integer, n, the size of the array.
The second line contains n space-separated integers that describe arr[n].

Constraints

0 < n < 100

-100 < arr[I] < 100

Output Format

Print the following  lines, each in decimals:

  1. the proportion of positive values
  2. the proportion of negative values
  3. proportion of zeros

Sample Input

STDIN           Function
-----           --------
6               arr[] size n = 6
-4 3 -9 0 4 1   arr = [-4, 3, -9, 0, 4, 1]

Sample Output

0.500000
0.333333
0.166667
HackerRank Plus Minus Problem Solution
HackerRank Plus Minus Problem Solution

Plus Minus C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int i, n, temp;
    int neg = 0, pos = 0, zero = 0;

    scanf("%d", &n);

    for(i = 0; i < n; i++) {
        scanf("%d", &temp);

        if (temp > 0) {
            pos++;
        } else if (temp < 0) {
            neg++;
        } else {
            zero++;
        }
    }

    printf("%.3f\n%.3f\n%.3f\n", (float) pos / n, (float) neg / n, 
           (float) zero / n);
    
    return 0;
}

Plus Minus C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
#define dd double

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    ll n, zeros=0, pos=0, neg=0;
    cin>>n;
    for(int i=0; i<n; i++){
        ll idx;
        cin>>idx;
        if(idx == 0)zeros++;
        else if(idx<0)neg++;
        else pos++;
    }
    cout<<(dd)((dd)(pos)/(dd)(n))<<endl;
    cout<<(dd)((dd)(neg)/(dd)(n))<<endl;
    cout<<(dd)((dd)(zeros)/(dd)(n))<<endl;
    return 0;
}

Plus Minus C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        int input = Int32.Parse(System.Console.ReadLine());
        string[] elements = System.Console.ReadLine().Split(' ');
        int pos = 0, neg = 0, zero = 0;
        for (int i=0; i<input; i++){
            int num = Int32.Parse(elements[i]);
            if(num>0) 
                pos++;
            else if(num<0)
                neg++;
            else 
                zero++;
        }
        System.Console.WriteLine((pos/(double)input));
        System.Console.WriteLine((neg/(double)input));
        System.Console.WriteLine((zero/(double)input));
    }
}

Plus Minus Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'plusMinus' function below.
     *
     * The function accepts INTEGER_ARRAY arr as parameter.
     */
     

    public static void plusMinus(List<Integer> arr) {
    // Write your code here
        int posCount = 0; 
        int negCount = 0;
        int zeroCount = 0;
        int total = arr.size(); 
        for(int i =0; i < total; i ++){
            if(arr.get(i) > 0){
                posCount ++;
            } else if (arr.get(i) == 0){
                zeroCount ++; 
            } else{
                negCount ++; 
            }
            
        } 
        
        double p = (double)posCount/total; 
        double n = (double)negCount/total; 
        double z = (double)zeroCount/total; 
        System.out.println((double)Math.round(p * 1000000d) / 1000000d
); 
        System.out.println((double)Math.round(n * 1000000d) / 1000000d
); 
        System.out.println((double)Math.round(z * 1000000d) / 1000000d
); 

 
         

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        Result.plusMinus(arr);

        bufferedReader.close();
    }
}

Plus Minus JavaScript Solution

var _input = "";

Array.prototype.peek = function () {
    if (this.length == 0)
        return null;

    return this[this.length - 1];
}

var processData = function (input) {
    
    //console.log("loading vlaues");

    var lines = input.split('\n');
    var count = parseInt(lines.shift());
    var values = lines
    .shift()
    .split(' ')
    .map(function (v) { return parseInt(v) });
    
    var pos = 0, neg = 0, zero = 0;

    values.forEach(function (v) {
        if (v > 0)
            pos++;
        else if (v < 0)
            neg++;
        else
            zero++;
    });

    console.log((pos / values.length).toFixed(3));
    console.log((neg / values.length).toFixed(3));
    console.log((zero / values.length).toFixed(3));
}

// get the input data
if (_input.length == 0) {
    process.stdin.resume();
    process.stdin.setEncoding("ascii");
    process.stdin.on("data", function (input) {
        _input += input;
    });
    
    process.stdin.on("end", function () {
        processData(_input);
    });
}
else
    processData(_input);

Plus Minus Python Solution

n = int(input())
positives = negatives = zeroes = 0
for i in [int(x) for x in input().split(' ')]:
    if i > 0:
        positives += 1
    elif i < 0:
        negatives += 1
    else:
        zeroes += 1

print("{:3f}".format(positives/n))
print("{:3f}".format(negatives/n))
print("{:3f}".format(zeroes/n))

Other Solutions

  • HackerRank Staircase Problem Solution
  • HackerRank Mini-Max Sum Problem Solution
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post

Leave a Reply

You must be logged in to post a comment.

  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes