I have solved a seemingly easy problem:
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below: $$\begin{bmatrix} 1\, 1\, 1 \\ 2 \, 3\, 3 \\ 0\,1\,0\end{bmatrix}$$
The left-to-right diagonal = \$0+3+1=4\$. The right to left diagonal \$1+3+0=4\$. Their absolute difference is \$0\$.
However, I am a beginner in C and had some troubles. It took me way too long :D. Also, I tried to abstract the problem on a higher level - which does not mean it is high. However, I am not sure how far I should abstract the problem in such challenges.
How well/bad is this code written?
Is the code abstract enough?
How can you solve such challenges more quickly?
int addDiagonal(int from_X,int to_X,int from_Y, int to_Y, int** arr){
int sum = 0;
int dirX = to_X - from_X;
if(dirX < 0) dirX = -1;
else if(dirX > 0) dirX = 1;
int dirY= to_Y - from_Y;
if(dirY < 0) dirY = -1;
else if(dirY > 0) dirY = 1;
while(from_X != to_X){
sum+=arr[from_X][from_Y];
from_X += dirX;
from_Y += dirY;
}
sum+=arr[from_X][from_Y];
return sum;
}
int diagonalDifference(int arr_rows, int arr_columns, int** arr) {
int left_to_right = addDiagonal(0,arr_columns-1,0,arr_rows-1,arr);
int right_to_left = addDiagonal(0, arr_columns-1,arr_rows-1,0,arr);
if(left_to_right - right_to_left > 0) return left_to_right - right_to_left;
return right_to_left - left_to_right;
}