Member-only story

JavaScript Interview: plusMinus function

Marika Lam
1 min readJun 21, 2024

--

Introduction

In this interview question, it’s important to know how to loop through an array, compare values and print a number based on the number of decimal places using .toFixed(..).

Prompt

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.

Print the following lines, each to decimals:

  1. proportion of positive values
  2. proportion of negative values
  3. proportion of zeros

Solution

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});

process.stdin.on('end', function() {
inputString = inputString.split('\n');

main();
});

function readLine() {
return inputString[currentLine++];
}

/*
* Complete the 'plusMinus' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/

function plusMinus(arr) {
// Write your code here
let countZero = 0;
let countPos = 0;
let countNeg = 0;

arr.forEach((num, numIndex) => {
if (num == 0){
countZero++;
} else if (num > 0){
countPos++;
} else if (num < 0){
countNeg++;
}
})

const calculateZero = countZero/arr.length;
const calculatePos = countPos/arr.length;
const calculateNeg = countNeg/arr.length;

console.log(calculatePos.toFixed(6));
console.log(calculateNeg.toFixed(6));
console.log(calculateZero.toFixed(6));
}

function main() {
const n = parseInt(readLine().trim(), 10);

const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

plusMinus(arr);
}

--

--

No responses yet