Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by witmolif
def count_neighbours(grid, row, col):
possible_n = (
(-1, -1), (-1,0), (-1, 1),
(0, -1), (0, 1),
(1 ,-1), (1, 0), (1, 1)
)
field_width = len(grid[0])
field_height = len(grid)
nb_num = 0
for n in possible_n:
if (
0 <= n[0] + row < field_height and
0 <= n[1] + col < field_width and
grid[n[0] + row][n[1] + col] == 1
):
nb_num = nb_num + 1
return nb_num
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
assert count_neighbours(((1, 0, 0, 1, 0),
(0, 1, 0, 0, 0),
(0, 0, 1, 0, 1),
(1, 0, 0, 0, 0),
(0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
assert count_neighbours(((1, 1, 1),
(1, 1, 1),
(1, 1, 1),), 0, 2) == 3, "Dense corner"
assert count_neighbours(((0, 0, 0),
(0, 1, 0),
(0, 0, 0),), 1, 1) == 0, "Single"
May 5, 2016