fix comparing zero and negative number javascript

Viewed 51

i got a problem while finishing this task. https://www.hackerrank.com/challenges/30-2d-arrays/problem. It is because while trying to finish with this algorithm, i got weird result.

function main(arr) {  
    let max;
    let sum;
    
    for(let a=0; a<arr.length-2; a++){
        for(let b=0; b<arr.length-2; b++){
            sum = 
            arr[a][b] + arr[a][b+1] + arr[a][b+2] + 
            arr[a+1][b+1] + 
            arr[a+2][b] + arr[a+2][b+1] + arr[a+2][b+2];
            console.log(sum);
            if(!max || sum > max){
                max = sum;
            }
        }        
    }
    console.log(max)
}

main([
    [-1,  1, -1,  0,  0, 0],
    [ 0, -1,  0,  0,  0, 0],
    [-1, -1, -1,  0,  0, 0],
    [ 0, -9,  2, -4, -4, 0],
    [-7,  0,  0, -2,  0, 0],
    [ 0,  0, -1, -2, -4, 0],
]);

i got result -2 instead of 0. that mean negative number here > 0. why this happen?

1 Answers

This is happening because of the !max part in your code. As you can see when max === 0 in that case the if part becomes,

if(!0 && -9 > 0) {

}

Although -9>0 is false but as !0 === true, the if block becomes,

if(!false || false) => if(true || false) => if(true)

That is why we are updating the max value.

Now to solve your problem what you can do is set max = -Infinity at the very first line of your code and remove the !max part from the if block. So your method will be,

function main(arr) {  
    let max = -Infinity;
    let sum;
    
    for(let a=0; a<arr.length-2; a++){
        for(let b=0; b<arr.length-2; b++){
            sum = 
            arr[a][b] + arr[a][b+1] + arr[a][b+2] + 
            arr[a+1][b+1] + 
            arr[a+2][b] + arr[a+2][b+1] + arr[a+2][b+2];
            console.log(sum);
            if( sum > max){
                max = sum;
            }
        }        
    }
    console.log(max)
}

main([
    [-1,  1, -1,  0,  0, 0],
    [ 0, -1,  0,  0,  0, 0],
    [-1, -1, -1,  0,  0, 0],
    [ 0, -9,  2, -4, -4, 0],
    [-7,  0,  0, -2,  0, 0],
    [ 0,  0, -1, -2, -4, 0],
]);

Related