How to check if a matrix is Toeplitz or not in Node.js

1 Answer

0 votes
// A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements

function isToeplitz(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
     
    for (let i = 1; i < rows; i++) {
        for (let j = 1; j < cols; j++) {
            console.log(i + " " + j + " - " + matrix[i][j] + " : " + matrix[i - 1][j - 1]);
            if (matrix[i][j] != matrix[i - 1][j - 1]) {
                return false;
            }
        }
        console.log("-----------");
    }
     
    return true;
}
         
const matrix = [
    [2, 5, 9, 8], 
    [4, 2, 5, 9], 
    [7, 4, 2, 5], 
    [0, 7, 4, 2], 
    [6, 0, 7, 4]];
     
    if (isToeplitz(matrix)) {
        console.log("Matrix is a Toeplitz");
    }
    else {
        console.log("Matrix is not a Toeplitz");
    }
 
 
  
  
  
/*
run:
     
1 1 - 2 : 2
1 2 - 5 : 5
1 3 - 9 : 9
-----------
2 1 - 4 : 4
2 2 - 2 : 2
2 3 - 5 : 5
-----------
3 1 - 7 : 7
3 2 - 4 : 4
3 3 - 2 : 2
-----------
4 1 - 0 : 0
4 2 - 7 : 7
4 3 - 4 : 4
-----------
Matrix is a Toeplitz
         
*/

 



answered Jan 23, 2024 by avibootz
edited Jan 23, 2024 by avibootz

Related questions

1 answer 86 views
1 answer 101 views
1 answer 115 views
1 answer 91 views
1 answer 112 views
1 answer 89 views
1 answer 120 views
...