This is my function, really messy, just trying to figure out how to get an answer, and then optimize it.
But basically you have to subtract the sum of each character in two diagonal lines in a matrix.
r is the matrix's size (f.e 3 = 3 rows and 3 columns)
and then you enter each of the characters. so the input should look something like
3
11 2 4
4 5 6
10 8 -12
so in the end, i get leftD = 4 and rightD = 19.
abs(4-19) should be 15 but for some reason i keep getting 1, even though i tried like a million different versions.
(This is a problem from hackerrank )
using namespace std;
int diagonalDifference(vector<vector<int> > arr)
{
int r;
int c;
int leftD = 0;
int rightD = 0;
int diff;
cin >> r;
int x = 0;
for (int i = 0; i < r; i++) {
arr.push_back(vector<int>());
for (int j = 0; j < r; j++) {
cin >> x;
arr[i].push_back(x);
}
}
for (int i = 0; i < r; i++) {
leftD += arr[i][i];
}
for (int i = 1; i < r - 1; i++) {
rightD += arr[0][r - 1] + arr[i][i] + arr[r - 1][0];
}
diff = abs(leftD - rightD);
return diff;
}
int main()
{
vector<vector<int> > arr;
diagonalDifference(arr);
cout << diagonalDifference;
}