Algorithm


Problem Name: Algorithms - Plus Minus

Problem Link: https://www.hackerrank.com/challenges/plus-minus/problem?isFullScreen=true

In this HackerRank Functions in Algorithms - Java programming problem solution,

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 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 negative and one zero. Their ratios are 2 / 5 = 0.400000; 2 / 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 <= 100

Output Format

Print the following 3 lines, each to 6 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

 

 

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>

int main() {
  int n, k;
  float pos = 0, neg = 0;

  scanf("%d", &n);
  for (int i = 0; i  <  n; i++) {
    scanf("%d", &k);
    if (k  <  0) {
      neg++;
    } else if (k > 0) {
      pos++;
    }
  }
  printf("%f\n%f\n%f", pos / n, neg / n, (n - pos - neg) / n);
  return 0;
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <bits/stdc++.h>
using namespace std;
 int p=0;int m=0;int z=0;
int main()
{  int n;
 cin>>n;
 int ar[n];
 for(int i = 0; i  <  n; i++)
 {
     cin >> ar[i];
     
 }  
    for(int i = 0; i  <  n; i++)
    {   if(ar[i] > 0)
        p++;
     else if(ar[i] < 0)
     m++;
     
     else z++;
           
    }
 double a1,a2,a3;
 a1 = double(p)/double(n);a2 = double(m)/double(n);a3 = double(z)/double(n>;
 cout << a1 << "\n" << a2 << "\n" << a3;
         
    return 0;
}

Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


import java.util.Scanner;

public class averageratio {

// Java program to find the ratio of positive,
// negative, and zero elements in the array.



    // Function to find the ratio of
    // positive, negative, and zero elements
   public  static void positiveNegativeZero(int[] arr)
    {

        // Store the array length into the variable len.
        int len = arr.length;

        // Initialize the postiveCount, negativeCount, and
        // zeroCountby 0 which will count the total number
        // of positive, negative and zero elements
        float positiveCount = 0;
        float negativeCount = 0;
        float zeroCount = 0;

        // Traverse the array and count the total number of
        // positive, negative, and zero elements.
        for (int i = 0; i  <  len; i++) {
            if (arr[i] > 0) {
                positiveCount++;
            }
            else if (arr[i]  <  0) {
                negativeCount++;
            }
            else if (arr[i] == 0) {
                zeroCount++;
            }
        }

        // Print the ratio of positive,
        // negative, and zero elements
        // in the array up to four decimal places.
        System.out.printf("%1.6f ", positiveCount / len);
        System.out.println();
        System.out.printf("%1.6f ", negativeCount / len);
        System.out.println();
        System.out.printf("%1.6f ", zeroCount / len);
        System.out.println();
    }

    // Driver Code.
    public static void main(String args[])
    {
      //  System.out.println("Enter the elements size for Ist test case");
        Scanner sc = new Scanner(System.in);
        int n= sc.nextInt();


        // Test Case 1:
        int a1[]= new int[n] ;
        for (int i = 0; i  <  n; i++){
                a1[i] = sc.nextInt();
                }




       // int[] a1 = { 2, -1, 5, 6, 0 };
        positiveNegativeZero(a1);


        // Test Case 2:
       /* int[] a2 = { 4, 0, -2, -9, -7, 1 };
       positiveNegativeZero(a2);  */
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with C# Programming

Code - C# Programming


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution {

    static void plusMinus(int[] arr) {
        int n = arr.Length;
        int positives = arr.Where(x => x > 0).Count();
        int negatives = arr.Where(x => x  <  0).Count();
        int zeroes = arr.Where(x => x == 0).Count();
        
        float positiveFraction = (float)positives / (float)n;
        float negativeFraction = (float)negatives / (float)n;
        float zeroFraction = (float)zeroes / (float)n;
        
        Console.WriteLine(positiveFraction);
        Console.WriteLine(negativeFraction);
        Console.WriteLine(zeroFraction);
    }

    static void Main(string[] args) {
        int n = Convert.ToInt32(Console.ReadLine());

        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
        plusMinus(arr);
    }
}
Copy The Code & Try With Live Editor

#5 Code Example with Python Programming

Code - Python Programming


import math
import os
import random
import re
import sys

# Complete the plusMinus function below.
def plusMinus(arr):
    pos=0
    neg=0
    neu=0
    for i in range(len(arr)):
        if(arr[i]>0):
            pos+=1
        elif(arr[i]==0):
            neu+=1
        else:
            neg+=1
    print(pos/len(arr))
    print(neg/len(arr))
    print(neu/len(arr))

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

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

    plusMinus(arr)
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Diagonal Difference in Java solution in Hackerrank - Hacerrank solution Java
Next
[Solved] Staircase in Java solution in Hackerrank - Hacerrank solution Java