Skip to content

An efficient way to check index out of bounds

I have an n x n 2D array, and need to connect random points to four neighbors (sorry I added the picture, but it seems one has to click on the link for the image to show).

Click to see the image

I would like to use code like this:

connect(p, p - n);
connect(p, p + n);
connect(p, p - 1);
connect(p, p + 1);

The problem I am having now is the index out of bounds for the ones on the edge. Originally I created array of size (n + 2) * (n + 2) to resolve the issue. That preserved the simplicity of the code, however I failed the storage requirement for the assignment. The array has to be n * n.

I researched and revised my algorithm

connect(grid[i][j], grid[Math.max(0, i-1)][j]);
connect(grid[i][j], grid[Math.min(n - 1, i+1)][j]);
connect(grid[i][j], grid[i][Math.max(0, j-1)]);
connect(grid[i][j], grid[i][Math.min(n - 1, j+1)]);

Right now, it would connect the point to itself it is out of bounds.My question is — is there a better/cleaner way to check if indices out of bounds? Thank you all.



I would personally goes for:

connect(grid, i, j, i - 1, j);

And have connect does this:

void connect(Point[][] grid, int x1, int y1, int x2, int y2) {
  if (x2 < 0 || y2 < 0  || 
      x2 >= grid.length || y2 >= grid.length) { // see note
    return; // nothing to do out of bounds
  connect(grid[x1][y1], grid[x2][y2]);  

It fully assumes that your grid is a matrix of N*N.

You could also don’t care about checking:

void connect(Point[][] grid, int x1, int y1, int x2, int y2) {
  try {
    connect(grid[x1][y1], grid[x2][y2]);  
  } catch (ArrayIndexOutOfBoundException e) {
    // nasty

I do think it is nasty because catching tend to cost more than checking – even if the check is done twice.

3 People found this is helpful