Search code examples
javascriptmatrix

Matrix elements sum


I want to get the sum of the matrix elements, except for those over which the number 0, and get error: Uncaught TypeError: Cannot set property '0' of undefined

function matrixElementsSum(matrix) {
let s = 0;
for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j <= matrix.length; j++) {
        if (matrix[i][j] == 0) {
            matrix[i+1][j] = 0;
        }
        s += matrix[i][j]
    }
}
return s
}
console.log(matrixElementsSum([[0, 1, 2, 0], 
                               [0, 3, 2, 1], 
                               [2, 0, 2, 3]]))

Solution

  • Your loop counter i should iterate over number of rows and j should iterate over number of columns. Also before setting matrix[i+i][j] to 0, you should also check if i+1 < matrix.length (number of rows)

    function matrixElementsSum(matrix) {
        let s = 0;
        for (var i = 0; i < matrix.length; i++) {
            for (var j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0 && i+1 < matrix.length) {
                    matrix[i+1][j] = 0;
                }
                s += matrix[i][j]
            }
        }
        return s
    }