I am trying to solve the Plus Minus problem in HackerRank using Typescript. I am getting NaN as result in first two print statements, however, the last one is working. This is my solution:
function plusMinus(arr: number[]): void {
// Write your code here
let pos: number, neg: number, zero: number = 0;
for (let i=0; i< arr.length; i ){
if(arr[i]>0){
pos =1;
}
else if(arr[i]<0){
neg =1;
}
else{
zero =1;
}
}
let len: number = arr.length;
let posRatio = (pos/len).toFixed(6);
let negRatio = (neg/len).toFixed(6);
let zeroRatio = (zero/len).toFixed(6);
console.log(posRatio);
console.log(negRatio);
console.log(zeroRatio);
}
Here is the output:
Compiler Message
Wrong Answer
Input (stdout)
6
-4 3 -9 0 4 1
Your Output (stdout)
NaN
NaN
0.166667
Expected Output
0.500000
0.333333
0.166667
Can anyone help me out to understand what the problem might have been?
CodePudding user response:
let pos: number, neg: number, zero: number = 0;
You only defined a default value for zero
in the above line. In JS (or TS), the default value of any variable is undefined
unless you explicitly set one.
undefined 1
is NaN.
console.log(undefined 1)
CodePudding user response:
Issue is in your value initialization.
let pos: number, neg: number, zero: number = 0;
If you would log this you will get
pos=undefined
neg=undefined
zero=0
and now if you try to add number with undefined it will give you NaN
Initialize pos, neg and zero to 0 properly.