Programing Trick to Avoid Checking Out of Bounds Index for 2d Array

By Xah Lee. Date: .

trick to avoid checking out of bounds index for 2d array

Here's a programing trick. If you are accessing a 2D array (e.g. matrix), such that you need to process each element with respect to its surrounding elements, you have the issue of checking boundary condition of elements in first row, last row, first column, last column. Because they do not have neighbors.

you can avoid out of bound check by padding the matrix.

for example, problems like programing Game of Life, or games on a grid, or Advent of Code Day 3 problem 1. Xah Talk Show 2023-12-11 Advent of Code Day 3, Live Coding, in WolframLang

And in Wolfram Language [see Wolfram Language in Depth] , there's a single function to do that. ArrayPad

The out of bound check is nasty, because you have to do special if cases, 4 of them, and you need to check for every element. But once you pad the matrix, you no need out of bound check, makes your code elegant.

this padding technique applies to rectangular array or matrix of any dimension, and char array, such as multi-line string and each line has the same number of characters.