HackerRank Solutions

HackerRank - Plus Minus

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.

In this program we need to full fill two requirement

1) Find ratio of positive, negative and zero.

In mathematics, a ratio shows how many times one number contains another.

So, the formula to find the ratio is (total occurrence of element / total no of element)

Suppose, array has integers as follow:

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

So, the occurrence of 1 is 2 times, 0 is 1 times and -1 is 2 times

and the ratios are as follow:

for 1 : 2/5 = 0.4

for -1 : 2/5 = 0.4

for 0 : 1/5 = 0.2

2) We have to display result in with 6 digits after point(.) i.e. 0.400000.

function plusMinus(arr) {
     // Write your code here
     let divisible = arr.length;
     let positive = 0;
     let negative=0;
     let neutral =0;
     arr.forEach(ar=>{
          if(ar >0){
               positive++;
          }else if(ar<0){
               negative++;
          }else if(ar==0){
               neutral++;
          }
     })
     console.log((positive/divisible).toPrecision(6))
     console.log((negative/divisible).toPrecision(6))
     console.log((neutral/divisible).toPrecision(6))
}
                    

In the above code we iterate each element of the array and check if the element is positive negative or zero (neutral). If it is positive we increment positive variable, if it is negative we increment negative variable and if it is zero we increment neutral variable.

Now, we will divide all variable with total no of element in the array and as we need 6 digit after point we will useĀ toPrecision(6)