Plus Minus | HackerRank Solution

Hello coders, today we are going to solve Plus Minus HackerRank Solution which is a Part of HackerRank Algorithms Series.

Plus Minus

Task

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 6 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 10-4 are acceptable.

Example

arr = [1, 1, 0, -1, -1]
There are n = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.4000002/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:

0.400000
0.400000
0.200000

Function Description

Complete the plusMinus function in the editor below.

plusMinus 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 to  decimals:

  1. proportion of positive values
  2. 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

Explanation

There are 3 positive numbers, 2 negative numbers, and 1 zero in the array.
The proportions of occurrence are positive: 3/6 = 0.500000, negative: 2/6 = 0.333333 and zeros: 1/6 = 0.166667.

Solution – Plus Minus

C++

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);

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

void plusMinus(vector<int> arr) {
    float countPositive = 0;
    float countNegative = 0;
    float n = arr.size();

    for(int i;i<n;i++) {
        if (arr[i] > 0)
            countPositive++; 
        else if (arr[i] < 0)
            countNegative++;        
    }
    float countZero = n - countNegative - countPositive;
    cout << setprecision(6) << countPositive/n << endl;
    cout << setprecision(6) << countNegative/n << endl;
    cout << showpoint << setprecision(6) << countZero/n << endl;
}


int main()
{
    string n_temp;
    getline(cin, n_temp);

    int n = stoi(ltrim(rtrim(n_temp)));

    string arr_temp_temp;
    getline(cin, arr_temp_temp);

    vector<string> arr_temp = split(rtrim(arr_temp_temp));

    vector<int> arr(n);

    for (int i = 0; i < n; i++) {
        int arr_item = stoi(arr_temp[i]);

        arr[i] = arr_item;
    }

    plusMinus(arr);

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

vector<string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}

Python

#!/bin/python3

import math
import os
import random
import re
import sys

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

def plusMinus(arr):
    positiveCounter = 0
    negetiveCounter = 0
    zeroCounter = 0

    for i in range (len(arr)):
        if arr[i] > 0:
            positiveCounter += 1
        elif arr[i] < 0 :
            negetiveCounter +=1
        else:
            zeroCounter += 1

    print("%f"%(positiveCounter / len(arr)))
    print("%f"%(negetiveCounter / len(arr)))
    print("%f"%(zeroCounter / len(arr)))
    # Write your code here

if __name__ == '__main__':
    n = int(input().strip())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)

Java

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 {
  public static int n;
    // Complete the plusMinus function below.
    static void plusMinus(int[] arr) {
        int c_neg=0;
        int c_pos=0;
        int c_zero=0;
     for(int i = 0 ; i<n ; i++)
     {
          if(arr[i]<0)
          {
            c_neg+=1;
          }
          if(arr[i]>0)
          {
            c_pos+=1;
          }
          if(arr[i]==0)
          {
            c_zero+=1;
          }

     }
      double pof_pos,pof_neg,pof_zero;
          pof_pos = (double)c_pos/(double)n;
           pof_neg = (double)c_neg/(double)n;
            pof_zero = (double)c_zero/(double)n;
            System.out.println(pof_pos);
             System.out.println(pof_neg);
              System.out.println(pof_zero);


    }

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

    public static void main(String[] args) {
         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();
    }
}

Disclaimer: The above Problem (Plus Minus) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *