How to find the sum of boundary elements of a matrix in JavaScript

1 Answer

0 votes
function getBoundarySum(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    let sum = 0;
    
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1) {
                sum += matrix[i][j];
            }
        }
    }
    
    return sum;
}
        
const matrix = [[1, 2, 3, 4], 
                [5, 6, 7, 8], 
                [9, 10, 11, 12]];

console.log(getBoundarySum(matrix));




/*
run:
   
65
   
*/

 



answered Jun 18, 2023 by avibootz

Related questions

1 answer 144 views
1 answer 179 views
1 answer 120 views
1 answer 104 views
1 answer 101 views
1 answer 112 views
...