Skip to content

Edvins Antonovs

Plus Minus code challenge

My approach to solving HackerRank’s Plus Minus Code Challenge code challenge.


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 places after the decimal.

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].

Output format

Print 3 lines with proportion of positive values, proportion of negative values and proportion of zeros, each to 6 decimals.

Sample input

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

Sample output

10.500000
20.333333
30.166667

Solution

Initially, we start by creating positive (pos), negative (neg), and zeros (zer) variables and assigning each variable to 0.

After that we loop through the given array and using Math.sign() we figure out whenever a number is positive, negative or zero. Then we just increment (++) the appropriate variable.

Finally, we divide each variable's value by array length (arr.length) and add use Number.toFixed(6) to format it to 6 decimals.

Solution complexity: O(n).

1function plusMinus(arr) {
2 let pos = 0,
3 neg = 0,
4 zer = 0;
5
6 for (let i = 0; i < arr.length; i++) {
7 if (Math.sign(arr[i]) === 1) pos++;
8 else if (Math.sign(arr[i]) === -1) neg++;
9 else if (Math.sign(arr[i]) === 0) zer++;
10 }
11
12 console.log((pos / arr.length).toFixed(6));
13 console.log((neg / arr.length).toFixed(6));
14 console.log((zer / arr.length).toFixed(6));
15}

Appendix

© 2024 by Edvins Antonovs. All rights reserved.