I don't know if I'm wording the problem correctly in the title. Basically, in a chess board, I need to find the diagonals a bishop can move on, and more specifically, the coordinates of those squares. So, given a grid of any size and a position in that grid (expressed in coordinates within the grid), I have to compute the coordinates of the diagonals of that initial position.
I'm using zero-based indexing, and the (row, column)
notation for coordinates.
For example, on a 8x8 grid, with starting position of (0, 0)
, the returned list should be [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7)]
.
On a 8x8 grid, with starting position of (3, 4)
, the returned list should be [(3, 4), (2, 3), (1, 2), (0, 1), (4, 5), (5, 6), (6, 7), (4, 3), (5, 2), (6, 1), (7, 0), (2, 5), (1, 6), (0, 7)]
This is my working program in Python 3:
def diagonals(coord, size):
limit = size - 1
coords = [coord]
row = coord[0]
col = coord[1]
while row > 0 and col > 0:
row -= 1
col -= 1
coords.append((row, col))
row = coord[0]
col = coord[1]
while row < limit and col < limit:
row += 1
col += 1
coords.append((row, col))
row = coord[0]
col = coord[1]
while row < limit and col > 0:
row += 1
col -= 1
coords.append((row, col))
row = coord[0]
col = coord[1]
while row > 0 and col < limit:
row -= 1
col += 1
coords.append((row, col))
return coords
coord = (3, 4)
size = 8
print(diagonals(coord, size))
Depending on the diagonal (4 cases), row and column are added or subtracted by one until the last square is reached, and everything is kept in a list, which in the end is returned.
It works, but it left me wondering if there's a simpler, different, better way of doing this, probably using linear algebra or something? And how about idiomatically, how can this be more Pythonic?