Mathematical formula to find adjacent items in a grid

1.7k Views Asked by At

I have a 3x3 grid of dots. Selecting any one of the 9 dots, I need to find out which of the remaining dots are adjacent to the first dot. So, if for example we chose the first dot in the first row (dot 0, numbering them from 0, left to right, moving down the rows), the adjacent dots would be dot 1,3,and 4:

[X, 1, 2]

[3, 4, 5]

[6, 7, 8]

and if we chose dot 4, all of the other dots would be adjacent.

[0, 1, 2]

[3, X, 5]

[6, 7, 8]

Is there a mathematical formula to calculate this adjacency?

Ideally, what I'd like to do is extend this concept to find a formula in which a user must select 5 dots in total, always picking an adjacent dot when available, and not permitted to reselect a dot, such as this:

[X, 1, 2]

[3, 4, 5]

[6, 7, 8]


[X, X, 2]

[3, 4, 5]

[6, 7, 8]


[X, X, 2]

[X, 4, 5]

[6, 7, 8]


[X, X, 2]

[X, X, 5]

[6, 7, 8]


[X, X, 2]

[X, X, X]

[6, 7, 8]

Additionally, calculating the number of possibilities available would be useful.

2

There are 2 best solutions below

0
On BEST ANSWER

Two dots are adjacent (ignoring diagonals) if they agree on one coordinate, and differ by one in the other.

Two dots are adjacent diagonally if they differ by one in each coordinate.

This can be expressed by the inequalities $$ \lvert x_1-x_2\rvert\leq 1\qquad\text{and}\qquad\lvert y_1-y_2\rvert\leq 1, $$ where $(x_1,y_1)$ and $(x_2,y_2)$ are the coordinates of the points in question.

0
On

Let $c$ be the number of columns in your array and $n$ the dot number that you are looking for neighbors for. The dot to the left (if there is one) is $n-1$. You can check if there is one by checking if $n$ is divisible by $c$. If it is, you are in the left column. The dot to the right is $n+1$ and there will be one unless $n+1$ is divisible by $c$. The dot above is $n-c$ and there is one if that is positive. The dot below is $n+c$ and there is on as long as that is not greater than the total number of dots. The diagonal ones are combinations of this-can you see how to do that?