Find neighbors of point in matrix

I am trying to make a simulation of Conway's Game Of Life with my matrix blocks (shameless plug) and I need to find the values of each point's neighbors to change it. This is how I am doing it now:

I know I made this, but I know there are many people on here who are much smarter than I am, and could figure this out easily. Thanks!

You could use a variable that changes by 1 if the point exists, so just do change sides by (point (x) (y) exists in matrix (world)? This would only work if the vale it reports is a boolean, or 1/0.

There's many,many different ways of calculating the number of neighbours but if you make your matrix only contain 1 or 0 for alive or dead then you don't need the if statements - you can just add up all the point values

Lots of interesting answers from different people.

My own preferred approach is to make an array that's n+2 long and wide, where n is the number of points you want to use, and use coordinates 2 to n+1 for the actual points:

(and whatever you want to do for each point in the c-slot). That way, every point has all eight neighbors existing in the array.

If the proper value for a nonexistent point is zero, then as cymplecy says, you can take advantage of the fact that Snap! doesn't give you an error message for a nonexistent index in a list, just have the n by n array, and in effect every point still has eight neighbors. But I learned to program in less forgiving languages, so I put the border in explicitly.

By the way, you can say untitled script pic (2) and the same for COLUMN to get all the neighbor coordinates (plus the point itself; if you don't want that you have to remove it from the resulting list of coordinate pairs).

yes! I was just going to suggest starting with something like this:

and if you want to only access coordinates that exist in the matrix, you could make it obey its dimensions:

note, this reporter includes the value of the given point itself. I always use something like that if I want to aggregate a "tile" inside a matrix, e.g. the average color for a "pixellate" effect in a photo. In that case I want the value of the given coordinate. If you only want the neighbors without the given coordinate you'd need to filter that single value out.

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