2d array finding neighbors c 2b 2b

Solutions on MaxInterview for 2d array finding neighbors c 2b 2b by the best coders in the world

showing results for - "2d array finding neighbors c 2b 2b"
Felipe
03 Mar 2020
1#include <stdio.h>
2
3#define ROWS 8
4#define COLS 8
5
6typedef int matrix_t[ROWS][COLS];
7
8static int sum(matrix_t &matrix, int row, int col)
9{
10    int sum = 0;
11    for (int i = -1; i < 2; i++)
12    {
13        for (int j = -1; j < 2; j++)
14        {
15            // skip center cell
16            if (i == j) continue;
17            // skip rows out of range.
18            if ( (i + row) < 0 || (i + row >= ROWS) continue;
19            // skip columns out of range.
20            if ( (j + col) < 0 || (j + col >= COLS) continue;
21            // add to sum.
22            sum += matrix[i + row][j + col];
23        }
24    }
25    return sum;
26}
27
28static int make(matrix_t &result, const matrix_t &source)
29{
30    for (int i = 0; i < ROWS; i++)
31        for (int j = 0; j < COLS; j++)
32            result[i][j] = sum(source, i, j);
33}
34
35// print a matrix to stdout.
36static int print(const matrix_t &source)
37{
38    for (int i = 0; i < ROWS; i++)
39    {
40        for (int j = 0; j < COLS; j++)
41            printf("\t%d", source[i][j]);
42        printf("\n");
43    }
44}
45
46// unit test
47int main(int argc, char *argv[])
48{
49    matrix_t result = {0};
50    const matrix_t source =
51    {
52        {1, 2, 3, 4, 5, 6, 7, 8},
53        {1, 2, 3, 4, 5, 6, 7, 8},
54        {1, 2, 3, 4, 5, 6, 7, 8},
55        {1, 2, 3, 4, 5, 6, 7, 8},
56        {1, 2, 3, 4, 5, 6, 7, 8},
57        {1, 2, 3, 4, 5, 6, 7, 8},
58        {1, 2, 3, 4, 5, 6, 7, 8},
59        {1, 2, 3, 4, 5, 6, 7, 8}
60    };
61    make(result, source);
62    puts("Source:");
63    print(source);
64    puts("Result:");
65    print(result);
66    return 0;
67}
68</stdio.h>