but, when it comes to other cases, my script (which is very basic) is parsed incorrectly. My method is call one function (error occurs here) which finds the lowest positive integer and save it in “x” variable. After that I call another function, find highest negative value and save it in “y”. The third function which is called compares the two variables (“y” is multiplied by (-1) during comparison) and the one which is lower is being printed (“y” is printed after it is multiplied by (-1) back again).
Here is the function in which error occurs (even though it works fine for 1st and 2nd test cases):
function findLowestPositiveValue(){
for(var i=0;i<=n;i++){
if(arr[i]>0){ //arr = temps.split(" ");
if(smallestPositiveValue > arr[i]){ //smallestPositiveValue is = 5526, as global var
smallestPositiveValue = arr[i];
}
}
}
}
When the input is [42,-5,12,21,5,24], the smallestPositiveValue is found to be 12. I can’t figure out why.
by the way, I copy-pasted the code to a local file in my PC and tried to run it with all the 6 test cases inputs - in all cases script worked fine and I received correct results So i’m not sure why this malfunctioning happens here…
The first thing that comes to my mind is that 12 start with a 1 and if you compare 12 to 5 first digit first that is the result you would get. It’s a kind of issue you can get when comparing numbers as strings.
Thanks Djoums (and everyone involved) - map() method fixed my code, it really was the issue of comparing string values instead of numbers. For some reason I thought that a string of numbers will be inserted into an array as numbers, not string values.
JavaScript being a dynamic language, you can never really assume a priori the variables types.
It’s one of the reasons why TypeScript is becoming more popular, unfortunately it’s not supported on CG at the moment.