Task 4 — Matrix Diagonal Processing
Objective
Create two functions that process a two-dimensional integer matrix relative to its main diagonal.
The first function must calculate the sum of all elements above the main diagonal.
The second function must calculate the sum of all elements below the main diagonal.
Input
The input is a two-dimensional collection of integers:
[][]int
Example:
data := [][]int{
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
}
This matrix contains five rows and five columns.
Main Diagonal
The main diagonal begins at:
[0][0]
and ends at:
[4][4]
For the example matrix, the diagonal positions are:
[0][0]
[1][1]
[2][2]
[3][3]
[4][4]
The values on the main diagonal are:
1
2
3
4
5
Function 1 — Sum Above the Diagonal
Create a function that calculates the sum of all elements located above the main diagonal.
An element is above the main diagonal when:
column index > row index
For example:
[0][1]
[0][2]
[0][3]
[0][4]
[1][2]
[1][3]
[1][4]
[2][3]
[2][4]
[3][4]
These positions are all above the main diagonal.
Using the example matrix, the values are:
2, 3, 4, 5,
3, 4, 5,
4, 5,
5
The function should return the sum of these values.
Function 2 — Sum Below the Diagonal
Create a second function that calculates the sum of all elements located below the main diagonal.
An element is below the main diagonal when:
row index > column index
For example:
[1][0]
[2][0]
[2][1]
[3][0]
[3][1]
[3][2]
[4][0]
[4][1]
[4][2]
[4][3]
These positions are all below the main diagonal.
Using the example matrix, the values are:
1,
1, 2,
1, 2, 3,
1, 2, 3, 4
The function should return the sum of these values.
Requirements
Create two separate functions:
- one function for summing elements above the main diagonal
- one function for summing elements below the main diagonal
The values located directly on the main diagonal must not be included in either result.
The implementation should determine the position of each element using its row and column indexes.
Matrix Representation
The matrix can be visualized as:
Columns
0 1 2 3 4
Row 0 1 2 3 4 5
Row 1 1 2 3 4 5
Row 2 1 2 3 4 5
Row 3 1 2 3 4 5
Row 4 1 2 3 4 5
The main diagonal is:
[0][0] = 1
[1][1] = 2
[2][2] = 3
[3][3] = 4
[4][4] = 5
Elements above the diagonal satisfy:
column > row
Elements below the diagonal satisfy:
row > column
Example Results
For the provided matrix:
Sum Above the Diagonal
2 + 3 + 4 + 5
+ 3 + 4 + 5
+ 4 + 5
+ 5
= 40
Expected result:
40
Sum Below the Diagonal
1
+ 1 + 2
+ 1 + 2 + 3
+ 1 + 2 + 3 + 4
= 20
Expected result:
20
Implementation Notes
The original task defines a square 5 x 5 matrix.
The implementation should correctly distinguish between:
- elements above the main diagonal
- elements on the main diagonal
- elements below the main diagonal
Do not include diagonal elements in either sum.
The exact function names and signatures are not specified by the original task and may be chosen by the developer.