Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moore Neighbourhood by jcg
#http://www.checkio.org/mission/count-neighbours/solve/
# utilitaries
def add(tuple1, tuple2):
return tuple(map(sum,zip(tuple1, tuple2)))
# try to minimize input errors in directions
DIR_NS = {'N': (-1, 0), 'S': (+1, 0)}
DIR_WE = {'W': (0, -1), 'E': (0, +1)}
DIR_ORTHO = dict((k,d[k]) for d in (DIR_NS, DIR_WE) for k in d)
DIR_DIAG = dict(
(k1+k2, add(DIR_NS[k1], DIR_WE[k2])) for k2 in DIR_WE for k1 in DIR_NS
)
DIR_ALL = dict((k,d[k]) for d in (DIR_ORTHO, DIR_DIAG) for k in d)
def contains(grid, pos):
# True if pos in grid
return 0 <= pos[0] < len(grid) and 0 <= pos[1] < len(grid[0])
def occuped(grid, pos):
# True if pos in grid and grid[pos]!=0
return contains(grid, pos) and grid[pos[0]][pos[1]] != 0
def count_neighbours(grid, row, col):
return sum(
map(
lambda pos: occuped(grid, pos),
(add((row, col), DIR_ALL[d]) for d in DIR_ALL)
)
)
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"
Oct. 1, 2014
Comments: