简体   繁体   中英

find sum of diagonal elements from given index in 2d array

I have to construct a 2d array with N,M rows and columns (N & M <= 5), then the user enters a certain index(location) like 2,3 (matrix[2][3]) it's assumed that the two numbers are in the bounds of the matrix. From then on I have to find the sum of the left and right diagonal that goes through the number, however the number is excluded from the sum.

So for example the 2d array is myArray[3][3]

*1* 15 *2*
2 *71* 8
*5* 22 *5*

So the user enters 1,1 that is myArray[1][1], in this case the number 71, the sum would be 1 + 5 + 2 + 5 ... And well my problem is how can i find those diagonals without going out of the bounds.

For the left top i would go:
row--
column--
while(row >= 0|| column >= 0)

For left bottom:
row++
colum++
while(row < N || column < M)

for right top:
row--
column++
while(row >= 0 || column < M)

for right bottom:
row++
column--
while(row < N || column >=0)

(this is bad written pseudo-code, sorry)

It works fine when I enter numbers that aren't in the top or bottom row, but in the cases that they are located there my program stops.

What you have is basically good pseudocode. My first thought was that you should be using &&'s instead of ||'s when determining if the location is out of bounds or not.

You also need some sort of way to exit early in case they give a bad location. Below is some code I wrote out quickly, and seems to work at a quick glance - I loop over every possible starting location including ones that are out of bounds.

#include <iostream>

const int N = 3;
const int M = 4;
int matrix[N][M] = {
        { 0, 1, 2, 3 },
        { 4, 5, 6, 7 },
        { 8, 9, 10, 11 }
};

int directional_sum(int row, int column, int row_inc, int column_inc)
{
    int sum = 0;

    if (row < 0 || column < 0 || row >= N || column >= M)
        return sum;

    int temp_row = row + row_inc;
    int temp_column = column + column_inc;
    while (temp_row >= 0 && temp_column >= 0 && temp_row < N && temp_column < M)
    {
        sum += matrix[temp_row][temp_column];

        temp_row += row_inc;
        temp_column += column_inc;
    }

    return sum;
}

int diagonal_sum(int row, int column)
{
    int sum = 0;
    sum += directional_sum(row, column,  1,  1);
    sum += directional_sum(row, column,  1, -1);
    sum += directional_sum(row, column, -1,  1);
    sum += directional_sum(row, column, -1, -1);

    return sum;
}

int main()
{
    for (int i = -1; i <= N; i++)
    {
        for (int j = -1; j <= M; j++)
        {
            std::cout << "Sum for [" << i << ", " << j << "]: " << diagonal_sum(i, j) << std::endl;
        }
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM