2

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 Answer 1

3

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],
]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.