-1

I'm having trouble figuring out how to identify the 1's in the array listed in my code below while taking into account the corners & edges of the array.

#include <stdio.h>
/* define grid size */
#define SIZE 7
int grid[SIZE][SIZE];
/* function to find the number of occupied adjacent cells */
int neighbors (int i, int j);
void main ()
{
  int i, j, n;
/* initialize the entire grid to be zero */
 for (i = 0; i < SIZE; i++)
    for (j = 0; j < SIZE; j++)
        grid[i][j] = 0;
/* introduce a few ones */
    grid[1][2] = 1;
    grid[2][2] = 1;
    grid[1][4] = 1;
    grid[2][4] = 1;
    grid[3][2] = 1;
    grid[3][3] = 1;
    grid[3][4] = 1;
    grid[5][3] = 1;
    grid[6][2] = 1;
for (i = 0; i < SIZE; i++)
   for (j = 0; j < SIZE; j++) {
      n = neighbors(i,j);
      printf ("Number of neighbors to element %d,%d =%d\n",i,j,n);
}
 return;
}
/* function to compute the neighbors */
int neighbors (int i, int j)

I figure that I can use if statements to alter how the code will run if i=0 or i=6, as well as if j=0 or j=6, but I'm not sure how to proceed. Any help would be much appreciated

2 Answers2

0

It is possible to wrap the direct access to the array in an abstraction layer. This layer can hide the access logic and additional checks. Something like:

int get_grid(int i, int j)
{
    if (i>=0 && i<SIZE)
        return grid[i][j];
    return 0;
}

And the calling function:

int neighbors (int i, int j)
{
    return get_grid(i-1, j-1) + get_grind(i-1, j) + ...
}
eyalm
  • 3,366
  • 19
  • 21
0

I suggest:

int neighbors (int i0, int j0)
{
    int imax = (i0 < SIZE) ? (i0 + 1) : SIZE;
    int jmax = (j0 < SIZE) ? (j0 + 1) : SIZE;
    int result = 0;

    for (int i = (i0 > 0) ? (i0 - 1) : 0; i <= imax; i++)
    {
        for (int j = (j0 > 0) ? (j0 - 1) : 0; j <= jmax; j++)
        {
            if ((i != i0 || j != j0) && grid[i][j] != 0)
            {
                result++;
            }
        }
    }

    return result;
}
jdarthenay
  • 3,062
  • 1
  • 15
  • 20
  • What is the C99 mode? I haven't learned that yet and am unsure how to compile to even test the code – Christian Littner Mar 25 '16 at 06:19
  • @Christian Littner I wonder why you ask this as a comment to my answer. C99 is a more recent standard, enabling it with `-std=C99` compile option will enable you some code not enabled by older standards. – jdarthenay Mar 25 '16 at 06:23