Iterate through 2D list, with 0,n mapping?

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.

I played with this for a bit and found that it is hard to see how to map a set of 8 bit arrangements to three sets, two of which have three members and one which has two. To wit, the neighbors of (0,0):

  • group one: (1,-1), (1,0), (1,1)
  • group two: (-1,-1), (-1,0), (-1,1)
  • group three: (0,-1), (0,1)

I’m only replying because I want to be notified if anyone does find a solution! :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.