graph laplacian matrix in javascript

index.tsx
// Assuming you have a graph represented as an adjacency matrix
const graph = [
  [0, 1, 0, 0],
  [1, 0, 1, 1],
  [0, 1, 0, 1],
  [0, 1, 1, 0]
];

// Function to calculate the Laplacian matrix
function calculateLaplacianMatrix(graph) {
  const laplacianMatrix = [];

  for (let i = 0; i < graph.length; i++) {
    laplacianMatrix[i] = [];
    for (let j = 0; j < graph.length; j++) {
      if (i === j) {
        let degree = 0;
        for (let k = 0; k < graph.length; k++) {
          degree += graph[i][k];
        }
        laplacianMatrix[i].push(degree);
      } else {
        laplacianMatrix[i].push(-graph[i][j]);
      }
    }
  }

  return laplacianMatrix;
}

console.log(calculateLaplacianMatrix(graph));
718 chars
32 lines

gistlibby LogSnag