Hi all,

Imagine you have a matrix (2D array), you pick a cell at coordinates (x, y), and that you want to iterate through its 8 neighbours. The order in which you iterate through its neighbours does not matters.

Option 1:

for i=-1, 1

for j=-1, 1

m[x + i ][y + j]

This will iterate through the neighbours and the (x,y) cell.

Option 2:

define a constant 2D array of MASKS {{-1,-1}, {-1,0}, {-1,1},{0, -1}…

for mask in MASKS:

m[x + mask[0]][y + mask[1]]

Option 3: <- this is where it gets interesting:

I want to create a mapping (using only binary operations) between the numbers 0 to 7 and the masks in option2. Namely I want my code to look like:

for i = 0, 7:

m[x + io1 - io2][y + io3 - io4]

where o1,o2,o3,o4 are binary operations using & and |

How could I find such a mapping ? Could this trick be generalized into an algorithms for more than 8 neighbours ?

Notice I am pretty sure it can be done, as I kind of intuitively assume.