Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Safe Coasts by Sim0000
def finish_map(field):
# generator for all positions in field
def field_pos():
for y in range(ysize):
for x in range(xsize):
yield (x, y)
# generator for all positions around land
def water_around_land():
for x, y in field_pos():
if m[y][x] != 'X': continue
for dx, dy in DIR:
x0, y0 = x + dx, y + dy
if 0 <= x0 < xsize and 0 <= y0 < ysize and m[y0][x0] == '.':
yield x0, y0
# mark all positions where dutchman can move
def dutch_man_move(x, y):
if 0 <= x < xsize and 0 <= y < ysize and m[y][x] == '.':
m[y][x] = 'D'
for dx, dy in((-1,0), (1,0), (0,-1), (0,1)):
dutch_man_move(x + dx, y + dy)
# initialize
DIR = ((-1,-1), (0,-1), (1,-1), (-1,0), (1,0), (-1,1), (0,1), (1,1))
xsize, ysize = len(field[0]), len(field)
m = [[c for c in row] for row in field]
# (1) mark safe around land
for x, y in water_around_land():
m[y][x] = 'S'
# (2) mark danger where dutchman can move
for x, y in field_pos():
if field[y][x] == 'D':
m[y][x] = '.'
dutch_man_move(x, y)
# (3) remaining positions are safe
return [''.join(row).replace('.', 'S') for row in m]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert isinstance(finish_map(("D..", "...", "...")), (list, tuple)), "List or tuple"
assert list(finish_map(("D..XX.....",
"...X......",
".......X..",
".......X..",
"...X...X..",
"...XXXXX..",
"X.........",
"..X.......",
"..........",
"D...X....D"))) == ["DDSXXSDDDD",
"DDSXSSSSSD",
"DDSSSSSXSD",
"DDSSSSSXSD",
"DDSXSSSXSD",
"SSSXXXXXSD",
"XSSSSSSSSD",
"SSXSDDDDDD",
"DSSSSSDDDD",
"DDDSXSDDDD"], "Example"
assert list(finish_map(("........",
"........",
"X.X..X.X",
"........",
"...D....",
"........",
"X.X..X.X",
"........",
"........",))) == ["SSSSSSSS",
"SSSSSSSS",
"XSXSSXSX",
"SSSSSSSS",
"DDDDDDDD",
"SSSSSSSS",
'XSXSSXSX',
"SSSSSSSS",
"SSSSSSSS"], "Walls"
Aug. 29, 2014
Comments: