In this problem, we will be provided a square matrix and we need to find the sum of the diagonals from “Left to Right” and then from “right to left”, and then we need to find the absolute difference between the sums of its diagonals. This can be explained with the help of the following table.
1 | 8 | 13 | 12 |
14 | 11 | 2 | 7 |
4 | 5 | 16 | 9 |
15 | 10 | 3 | 6 |
In the above table, the values of the diagonals from left to right are 1, 11, 16, and 6 and from right to left are 12,2,5,15 respectively.
So the sum of the diagonal from left to right is 1+11+16+6 = 34 and the sum of the diagonal from right to left is 12 + 2 +5 +15 = 34.
The absolute difference of the sum of diagonals is | 34 – 34 | = 0
Solution
I will proceed by writing a console application using the language C#. I will write a new method named MatrixDiagonalDifference and this method will accept a 2D List of integer.
If we see the table, we can see that if I iterate the table by using a simple loop from 0 to all rows, we can get value of all diagonal from left to right as depcited in following table:-
Iteration | i | Equation | Value |
---|---|---|---|
1 | 0 | matrix[0][0] | 1 |
2 | 1 | matrix[1][1] | 11 |
3 | 2 | matrix[2][2] | 16 |
4 | 3 | matrix[3][3] | 6 |
Now, we also need to get the values of all diagonals from “right to left”. If we see the matrix, we can see that if we iterate the matrix (which we are already doing in our loop) and get the value of the last column in the first iteration, and then decrement it on each iteration, we can get the value of the diagonal from right to left. This can be explained better in the following:-
Total Columns: 4
Value Of x = 4-1 = 3
ITERATION | i | x | EQUATION | VALUE |
---|---|---|---|---|
1 | 0 | 3 | matrix[0][3] | 12 |
2 | 1 | 2 | matrix[1][2] | 2 |
3 | 2 | 1 | matrix[2][1] | 5 |
4 | 3 | 0 | matrix[3][0] | 15 |
Code
public static int MatrixDiagonalDifference(List<List<int>> matrix)
{
int totalRows = matrix.Count;
int totalCols = matrix[0].Count;
int leftToRight = 0;
int rightToLeft = 0;
int x = totalCols - 1;
for (int i = 0; i < totalRows; i++)
{
leftToRight += (matrix[i][i]);
rightToLeft += (matrix[i][x]);
x--;
}
return Math.Abs(leftToRight - rightToLeft);
}
You can have the above method in your program and all you have to do is to pass a square matrix as an argument and it will do the job.