My approach to solving HackerRank’s Plus Minus Code Challenge code challenge.
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.
The first line contains an integer, n
, the size of the array.
The second line contains n
space-separated integers that describe arr[n]
.
Print 3 lines with proportion of positive values, proportion of negative values and proportion of zeros, each to 6 decimals.
1STDIN Function2----- --------36 arr[] size n = 64-4 3 -9 0 4 1 arr = [-4, 3, -9, 0, 4, 1]
10.50000020.33333330.166667
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}
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter