I'm trying to do an exercise from Hackerrank to compute an absolute difference of 2 diagonals from a square matrix. I have a code, but not perfect since it passes only 3/8 sample cases.
Below, is a sample test case, my code can solve this case, unfortunately I can't get access to different test cases including those that my code failed to solve because I don't have a premium account. Here's basically what the task is :
Dimension matrix : 3
11 2 4 | Diagonal 1 : 11 5 -12 -- sum_d1 = 4
4 5 6 | Diagonal 2 : 4 5 10 -- sum_d2 = 19
10 8 -12 | Abs difference diagonals : abs(sum_d1-sum_d2) = 15
Sample Input
3 11 2 4 4 5 6 10 8 -12
Sample Output
15
What I have tried:
Here's my code, I'm planning to treat this square matrix as a 1D array
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int n;
cin >> n; int size = n*n;
int arr[size];
int iter = 0;
for (int i = 0; i < n; i++){
cin >> arr[iter] >> arr[iter+=1] >> arr[iter+=1];
iter++;
}
int diag1 = 0, diag2 = 0;
int sum = 0;
int step1 = 0, step2 = 0;
for (int j = 0 ; j < n; j++){
diag1 += arr[step1];
step1 += (n+1);
step2 += (n-1);
diag2 += arr[step2];
}
sum = abs(diag1-diag2);
cout << sum << endl;
return 0;
}
Running :
3
11 2 4
4 5 6
10 8 -12
15 (correct answer)
I am aware that there are solutions online with various approaches. However, I want to try to solve this myself and want to know what did I miss and where did my code go wrong ? As I mentioned earlier, my code passes 3/8 sample cases, and I can't check failed cases because it requires premium account. Therefore, instead of a new approach, if possible please help me understand where / how did my code would fail. Thank you.
[UPDATE]
Solution was to modify the array insertion block to be :
for (int i = 0; i < n; i++){
for ( int j = n; j > 0; j--){
cin >> arr[iter];
iter++;
}
}
Thank you @CPallini for pointed out the mistake in my code.