Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate sum of numbers on matrix diagonal

Tags:

c#

matrix

I have a dynamic matrix and I need to to calculate sum of digits in this way:

0 1 2 3 4 5 6

10 11 12 13 14 15 16

20 21 22 23 24 25 26

30 31 32 33 34 35 36

40 41 42 43 44 45 46

50 51 52 53 54 55 56

60 61 62 63 64 65 66

I can't understand in which way I should compare i and j:

long result = 0;
for (int i = 0; i < len; i++)
{
    for (int j = 0; j < len; j++)
    {
        // only works for diagonal
        if (i == j) // should use j - 1 or i - 1? 
        {
            result += matrix[i][j];
        }
    }
}
like image 826
user5815164 Avatar asked Mar 14 '23 12:03

user5815164


1 Answers

no need to scan full matrix:

long result = 0;
for (int i = 0; i < len; i++)
{
     result += matrix[i][i];      // diagonal
     if (i < len - 1)             // stay within array bounds
        result += matrix[i][i+1]; // next to diagonal
}

modification without index check on every iteration:

// assign corner value from bottom row to result
long result = matrix[len-1][len-1];
// for each row (except last!) add diagonal and next to diagonal values
for (int i = 0; i < len-1; i++)    
     result += matrix[i][i] + matrix[i][i+1];
like image 61
ASh Avatar answered Mar 24 '23 14:03

ASh