DEV Community

Cover image for Plus Minus problem
Vibhor Singh
Vibhor Singh

Posted on

Plus Minus problem

Plus Minus problem is a part of 1 month of interview prep on HackerRank.
I joined it today.

It was the first of the lot hence it was seemingly easy but requires an important concept - floating point precision.
I used Javascript to solve it but you can also use any language which you want to use.
In Javascript, there is a function - toFixed()

The problem asks the solver to take the input as an array of integers and output the ratio of positives, negatives and zeroes; i.e. if an array [1,2,3,-4,-5,-6,0,0] is provided to you, you have to output the ratio of positives(array[i]) to length of array {in this case, it would be positives_ratio = 3/8 = 0.375} and same for negatives and zeroes.

Approach

  • Initialize few variables to count number of positives, negatives and zeroes {input is provided as an aray of integers};

let pos_count=0, neg_count=0, zero_count=0;

  • Use for loop {for of loop in Javascript} for traversal in the array and search for positive num, negative num and zeroes and increment their counts;
for(let i of array) {
    if(i<0) 
        neg_count += 1;
    else if(i>0) 
        pos_count += 1;
    else 
        zero_count += 1;
}
Enter fullscreen mode Exit fullscreen mode
  • Print the count_ratios on the console(or prompt screens) by dividing each count by length of array and use the toFixed() method to set the precision to 6 decimal places;

console.log((pos_count/array.length).toFixed(6));

Do same for negative count and zero count.

The problem is easy and suitable for beginners but requires the knowledge of floating point precision.

Top comments (0)