Member-only story

Plus Minus

Max N
3 min readNov 7, 2019

--

For today’s algorithm we are going to create a function called plusMinus.

The goal of this function is given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.

For example in the array [2, 5, -4, 0, -2], you can see that the length of the array is 5. Out of those 5 numbers, 2 are positive, 1 is negative, and 2 are negative.

Given what you know about the array and how many positive, negative, and zero numbers are there, the ratios are calculated as such:

2/5 = 0.400000 // positive
2/4 = 0.400000 // negative
1/5 = 0.200000 // zero

The outputs are scaled to six decimal places and the function should output each answer on a separate line.

Let’s begin by gathering all of our variables:

let pos = 0;
let neg = 0;
let zero = 0;
let total = arr.length;

The pos variable will calculate the number of positive numbers.

The neg variable will calculate the number of negative numbers.

The zero variable will calculate the number of zero numbers.

And the total variable will calculate the length of the array so you have a number to divide by.

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

Responses (1)