Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for The Lantern Festival by Moff
from collections import namedtuple
Cell = namedtuple('Cell', 'r c')
class River(object):
def __init__(self, field):
self.field = list(map(list, field))
self.lantern_paths = self.init_lanterns()
def init_lanterns(self):
lanterns = []
for i, v in enumerate(self.field[0]):
if v == '.':
lanterns.append([Cell(0, i)])
self.field[0][i] = 'o'
return lanterns
def fill_path(self, path, num):
marker = {0: 'X'}.get(num, '*')
while 1:
lantern = path[-1]
if lantern.r == len(self.field) - 1:
break
nei = self.neighbours4(lantern, '.')
neix = self.neighbours8(lantern, 'X*')
if not nei:
raise ValueError
for n in nei:
if any(x in neix for x in self.neighbours8(n, marker)):
self.field[lantern.r][lantern.c] = '-'
self.field[n.r][n.c] = 'o'
path.append(n)
break
for r, c in path:
self.field[r][c] = '*'
def neighbours(self, cell, delta, valids):
m = self.field
i, j = cell
return [Cell(ci, cj) for ci, cj in ((i + di, j + dj) for di, dj in delta)
if 0 <= ci < len(m) and 0 <= cj < len(m[0]) and m[ci][cj] in valids]
def neighbours4(self, cell, valids):
delta = [(1, 0), (0, 1), (0, -1), (-1, 0)]
return self.neighbours(cell, delta, valids)
def neighbours8(self, cell, valids):
delta = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
return self.neighbours(cell, delta, valids)
def lanterns_flow(field, minute):
river = River(field)
for i, path in enumerate(river.lantern_paths):
river.fill_path(path, i)
result = set()
for path in river.lantern_paths:
l = path[minute]
river.field[l.r][l.c] = 'o'
result.add(l)
for x in river.neighbours8(l, '*o'):
result.add(x)
return len(result)
Sept. 11, 2015