JavaScript Program for Diagonally Dominant Matrix



Diagonally Dominant Matrix refers to square matrix having magnitude of diagonal element in a row greater than or equal to the sum of magnitude of non-diagonal elements in that row.

In this article we are having a square matrix, our task is to write JavaScript program for diagonally dominant matrix. Users must be familiar with 2D matrix, nested for loop and conditional statement.

Diagonally Dominant Matrix

Formula:

$$\mathrm{|\:a_{ii}\:|\:\geq\:\displaystyle\sum\limits_{j ? i}\:|\:a_{ij}|}$$

for all i Where aij denotes the entry in the ith row and jth column

Example

Input:
[A] = 
    [[6, -2, 0, 0],
    [2, 8, -3, 0],
    [1, 2, 9, -4],
    [0, 1, -2, 7]]

Condition for Diagonally Dominant Matrix : 
    |a[i][i]| >= |a[i][j1]| + |a[i][j2]| + .... |a[i][jn]|
for i = 0,
    |a[0][0]| >= |a[0][1]| + |a[0][2]| + |a[0][3]|
    |6| >= |-2| + |0| + |0|
for i = 1,
    |a[1][1]| >= |a[1][0]| + |a[1][2]| + |a[1][3]|
    |8| >= |-2| + |-3| + |0|
for i = 2,
    |a[2][2]| >= |a[2][0]| + |a[2][1]| + |a[2][3]|
    |9| >= |1| + |2| + |-4|
for i = 3,
    |a[3][3]| >= |a[3][0]| + |a[3][1]| + |a[3][2]|
    |7| >= |0| + |1| + |-2|

Output: true, Diagonally Dominant Matrix

Steps for Diagonally Dominant Matrix

We will be following below mentioned steps to write javascript program for diagonally dominant matrix. It has time complexity of O(n^2) due to nested for loop and space complexity of O(1).

  • We have declared a 2D arrays as matrix and defined a function check() that takes matrix as argument.
  • Then we have used nested for loop where, outer for loop iterates over rows and inner loops iterates over columns of the matrix.
  • Then we have defined two variables i.e diagonal to store the diagonal elements of matrix and sum that stores the sum of elements of rows except diagonal element.
  • we have used if/else statement to check for non-diagonal elements and calculate their sum.
  • If the diagonal element is less than sum, false is returned, meaning given matrix is not diagonally dominant matrix.
  • After the loop ends, true is returned, meaning the given matrix has satisfied the condition to be diagonally dominant matrix.
  • The result is then displayed in web console using console.log() method.

Example

Here is a complete example code implementing above mentioned steps for diagonally dominant matrix using nested for loop.

const matrix = [
    [6, -2, 0, 0],
    [2, 8, -3, 0],
    [1, 2, 9, -4],
    [0, 1, -2, 7]
];
console.log(matrix);

function check(matrix) {
    for (let i = 0; i 

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2024-12-12T15:24:13+05:30

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements