0

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;
}
drescherjm
  • 10,365
  • 5
  • 44
  • 64

2 Answers2

3

You need to save the value returned from your function. At the moment you're just discarding it.

Try:

int result = diagonalDifference(arr);
cout << result;
Paul Mitchell
  • 3,241
  • 1
  • 19
  • 22
2

What you are doing here

diagonalDifference(arr);
cout << diagonalDifference;

is

  1. Call the function diagonalDifference and discard the result
  2. Print if the address of the function diagonalDifference is true (this will always be true)

Instead of this, you should print the result of function call (what is returned from the function).

cout << diagonalDifference(arr);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70