Task
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^-4 are acceptable.
Example
arr = [1,1,0,-1,-1]
There are n=5 elements (where n is the length of the array), two positive, two negative and one zero. Their ratios are ⅖=0.400000, ⅖=0.400000 and ⅕=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 n 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[i] <= 100
Output Format
Print the following 3 lines, each to 6 decimals:
- proportion of positive values.
- proportion of negative values.
- 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
Explanation
There are 3 positive numbers, 2 negative numbers, and 1 zero in the array. The proportions of occurrence are positive:3/6=0.500000, negative:2/6=0.333333, and zeros: ⅙=0.166667.
Solution
The task above is pretty simple. You will be given an array of numbers and the task is to:
- find the number of positive integers, negative integers and zero values.
- find the ratio or proportions the postive, negative and zero integers. To achieve this, divide the count of each category by the total number of items in the array (length of an array).
- print the ratio in the order that was listed above: positive, negative and zero.
function plusMinus(arr) {
// Write your code here
const counts = { "1": 0, "-1": 0, "0": 0 };
const ratioArr = [];
for (let i = 0; i < arr.length; i++) {
counts[Math.sign(arr[i])]++;
}
const orders = ["1", "-1", "0"];
for (const values of orders) {
const calc = counts[values] / arr.length;
const result = calc.toFixed(6);
ratioArr.push(result);
}
console.log(ratioArr.join('n'));
}
Code explanation
To solve this, we first need to loop through the array of numbers and categorize each number according to its sign. We need to store the counts for each category in an object with key value pairs. Where the key is going to be the category and the value will be the count. In this case we used the counts
object and gave it properties of "1","-1" and "0"
to represent the different categories. It also has default values of 0.
for (let i = 0; i < arr.length; i++) {
counts[Math.sign(arr[i])]++;
}
The code above loops through the elements in the array and updates the counts
object by increasing the value of the selected property by 1. The Math.sign()
method retuns whether a number is negative, positive or zero.
- If the number is positive, this method returns 1.
- If the number is negative, it returns -1.
- If the number is zero, it returns 0.
Hence why our counts object has keys of 1,-1 and 0. To read more on Math.sign() check this out.
Now JavaScript objects do not guarantee the order of keys the way arrays do. Numeric keys are treated like indices and are sorted in ascending numerical order. What this means is that when you log counts object above after looping through the elements, it rearranges the object and prints it out in this order 0,1,-1
instead of 1,-1,0
. To fix this issue, an array called orders
was created with the elements being the key of the counts object in the order we want it printed out.
const orders = ["1", "-1", "0"];
for (const values of orders) {
const calc = counts[values] / arr.length;
const result = calc.toFixed(6);
ratioArr.push(result);
}
This block of code loops through the orders array using the for...of
loop which iterates over the values of the array directly. For each value in the orders array:
- The code calculates the ratio of the count of numbers in that category,
counts[values]
,to the total number of elements in the array ,arr.length
. - The result is then formatted to six decimal places using
.toFixed(6)
, ensuring precision up to six decimal points as required. - The formatted ratio is added to the
ratioArr
array usingratioArr.push(result)
.
The next step is to print the items in the ratioArr with each element starting in a new line. To do this, the Array.join()
method is used to convert the array into a string. It takes an argument of "n"
as the separator. This separator ensures that each item is printed in a new line.
The solution has a linear time complexity, O(n), making it a good solution. Feel free to drop your solutions and thoughts the comments below.
Source link
lol