Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
VB
sum = matrix[i-1][j-1] + matrix[i-1][j] + matrix[i-1][j+1]
          + matrix[i][j-1] + matrix[i][j+1]
            + matrix[i+1][j-1] + matrix[i+1][j] + matrix[i+1][j+1] ;


i'm just know that . but i don't know how.
Posted
Comments
[no name] 22-Jan-15 22:33pm    
The question is not clear. You have got the correct 8 neighbours of element matrix[i][j] and you wish to sum them. Apart from checking for array out of bounds what is the problem?
Nguyen MinhHuy 24-Jan-15 11:02am    
I want to know how to print a new array (result array), with size of this new array is equal to old array. Each element of new array is the sum of 8 neighbour elements in old array.

1 solution

C++
#include <stdio.h>

#define ROWS 8
#define COLS 8

typedef int matrix_t[ROWS][COLS];

static int sum(matrix_t &matrix, int row, int col)
{
    int sum = 0;
    for (int i = -1; i < 2; i++)
    {
        for (int j = -1; j < 2; j++)
        {
            // skip center cell
            if (i == j) continue;
            // skip rows out of range.
            if ( (i + row) < 0 || (i + row >= ROWS) continue;
            // skip columns out of range.
            if ( (j + col) < 0 || (j + col >= COLS) continue;
            // add to sum.
            sum += matrix[i + row][j + col];
        }
    }
    return sum;
}

static int make(matrix_t &result, const matrix_t &source)
{
    for (int i = 0; i < ROWS; i++)
        for (int j = 0; j < COLS; j++)
            result[i][j] = sum(source, i, j);
}

// print a matrix to stdout.
static int print(const matrix_t &source)
{
    for (int i = 0; i < ROWS; i++)
    {
        for (int j = 0; j < COLS; j++)
            printf("\t%d", source[i][j]);
        printf("\n");
    }
}

// unit test
int main(int argc, char *argv[])
{
    matrix_t result = {0};
    const matrix_t source =
    {
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8},
        {1, 2, 3, 4, 5, 6, 7, 8}
    };
    make(result, source);
    puts("Source:");
    print(source);
    puts("Result:");
    print(result);
    return 0;
}
</stdio.h>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900