Is there any way to avoid this block of code?

I am reworking the minesweeper for practice and wrote this bit of code to avoid IndexOutOfBounds errors. Is there any way to avoid this, so I don’t need to explicitly write out the if statement of any possible error? I was thinking about making each array of 2 indexes large and just ignoring the first and last index. Am I missing something?

        if (row > 0 && col > 0)
            ray[row - 1][col - 1] += 1;
        if (row > 0)
            ray[row - 1][col] += 1;
        if (row > 0 && col < height - 1)
            ray[row - 1][col + 1] += 1;
        if (col > 0)
            ray[row][col - 1] += 1;
        if (col < height - 1)
            ray[row][col + 1] += 1;
        if (row < width - 1 && col > 0)
            ray[row + 1][col - 1] += 1;
        if (row < width - 1)
            ray[row + 1][col] += 1;
        if (row < width - 1 && col < height - 1)
            ray[row + 1][col + 1] += 1;
+5
source share
3 answers

Instead, you can use a loop and define boundaries once. Sort of:

int startRow = max(row - 1, 0);
int endRow = min(row + 1, width - 1);

int startCol = max(col - 1, 0);
int endCol = min(col + 1, height - 1);

for (int r = startRow; r <= endRow; r++)
   for (int c = startCol; c <= endCol; c++)
       if (r != row || c != col) //it looks like you want to skip this cell
           ray[r][c] += 1;

Alternatively, if the operation is reversible (as in this code, you add 1), you can simply cancel the operation for the middle cell after the loop. This would be more efficient, since it eliminates (no more) 12 comparisons if the operation itself is simple:

int startRow = max(row - 1, 0);
int endRow = min(row + 1, width - 1);

int startCol = max(col - 1, 0);
int endCol = min(col + 1, height - 1);

for (int r = startRow; r <= endRow; r++)
   for (int c = startCol; c <= endCol; c++)
       ray[r][c] += 1;

//reverse the operation for the middle cell
ray[row][col] -= 1;
+5

, if. (, , row > 0 .)

, 2 n , row 1 height col 1 width , .

, , row width col height, .

+2

Yes it can be done with a loop

for(int r=row-1; r<=row+1; r++)
 for(int c=col-1; c<=col+1; c++)
   if( r>=0 && r<ROWS && c>=0 && c<COLS && !(r==row && c==col) )
      ray[r][c]++;
0
source

All Articles