-1

I am trying to make some code so that a single element a matrix can reference elements adjacent to it. Sort of like how you can only move game pieces to spaces adjacent. For example, I want to be able to say something like:

if x matrix element is adjacent to y element:
     y_element_adjacent = True

I want to know how to accomplish the 'is adjacent' portion of this.

EDIT: I have tried making a list and assigning each element a number. So in a 100 element list (or a 10x10 game board), space 1x1 would be the 0th element and space 1x3 would be the 2nd element... Like this:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

11, 12, 13, 14, 15, 16, 17, 18, 19, 20

However, the problem with this is that if the x element was 10, my code would take + 1 to find an adjacent space, and 11 is NOT adjacent. I then realized that lists are not the correct way to do this and matrices would be a the way to go. I'm just a little confused on how I can use them differently than lists.

Any help is appreciated! Thanks.

Jerfy
  • 3
  • 4
  • 1
    There are many, many ways to do this, depending on how your code is organized. Can you be more specific about what you have and - more importantly - what you've tried yourself before asking this question? – TigerhawkT3 Jul 20 '16 at 23:43
  • Just take all 4 neighbors (+1 and -1 index for x, the same for y -> 2*2 combs; or 8 if diagonals are *adjacent*). But before indexing, check if within bounds (x+1 < x_length; x-1 >= 0; y+1 < y_length, y-1 >= 0) – sascha Jul 20 '16 at 23:45
  • Thanks for the comments. Edited with my original thought process. – Jerfy Jul 21 '16 at 15:17

1 Answers1

1

Here's a simple way to obtain indices of all adjacent elements.

from itertools import product, starmap

x, y = (x_coordinate, y_coordinate) # matrix values here
cells = starmap(lambda a,b: (x+a, y+b), product((0,-1,+1), (0,-1,+1)))

For an input of x,y = (1,1), this returns (list(cells)[1:]) containing [(1, 0), (1, 2), (0, 1), (0, 0), (0, 2), (2, 1), (2, 0), (2, 2)].

Such an implementation might be of interest in your particular scenario (determining to which places a certain game piece may move). If you want to include border checking, you might try

X = max_board_X
Y = max_board_Y    
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
                                   for y2 in range(y-1, y+2)
                                   if (-1 < x <= X and
                                       -1 < y <= Y and
                                       (x != x2 or y != y2) and
                                       (0 <= x2 <= X) and
                                       (0 <= y2 <= Y))]

Other solutions (and sources for these) may be found here: Determining neighbours of cell two dimensional list

Community
  • 1
  • 1
manan
  • 1,385
  • 13
  • 23