Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- import sys
- def walk(plan):
- x, y = 0, 0
- corners = [(0, 0)]
- directions = ((1, 0), (0, 1), (-1, 0), (0, -1))
- for d, l, c in plan:
- d, l = directions[int(c[-1])], int(c[0:-1], 16)
- x, y = x + l * d[0], y + l * d[1]
- corners.append((x, y))
- return corners
- def draw(corners):
- # ensure no line or corner directly abuts another to help the flood fill
- def expand(v):
- return sorted(set(v + [w - 1 for w in v] + [w + 1 for w in v]))
- xgrid = expand([p[0] for p in corners])
- ygrid = expand([p[1] for p in corners])
- xindex = dict((v, i) for i, v in enumerate(xgrid))
- yindex = dict((v, i) for i, v in enumerate(ygrid))
- index = [(xindex[x], yindex[y]) for x, y in corners]
- i0, j0 = index[0]
- field = [['.'] * len(xgrid) for y in range(len(ygrid))]
- field[j0][i0] = '#'
- for i1, j1 in index[1:]:
- if i0 != i1:
- for i in range(min(i0, i1), max(i0, i1) + 1):
- field[j0][i] = '#'
- if j0 != j1:
- for j in range(min(j0, j1), max(j0, j1) + 1):
- field[j][i0] = '#'
- i0, j0 = i1, j1
- return field, xgrid, ygrid
- def fill(field, row, col):
- q = [(row, col)]
- while q:
- r, c = q.pop()
- if 0 <= r < len(field) and 0 <= c < len(field[0]):
- if field[r][c] == '.':
- field[r][c] = 'o'
- q.append((r - 1, c))
- q.append((r + 1, c))
- q.append((r, c - 1))
- q.append((r, c + 1))
- def count(field, xgrid, ygrid):
- total = 0
- for y in range(len(field)):
- for x in range(len(field[0])):
- if field[y][x] in ('#', '.'):
- dy = ygrid[y + 1] - ygrid[y] if field[y + 1][x] != 'o' else 1
- dx = xgrid[x + 1] - xgrid[x] if field[y][x + 1] != 'o' else 1
- total += dx * dy
- return total
- def fieldstr(field):
- return '\n'.join(''.join(f) for f in field)
- def advent_day18_part1(lines):
- plan = []
- for line in lines:
- m = re.search(r'^(\S+) (\S+) \(#(\S+)\)', line)
- if m:
- d, l, c = m.groups()
- l = int(l)
- plan.append((d,l,c))
- corners = walk(plan)
- print()
- print('corners')
- print(corners)
- field, xgrid, ygrid = draw(corners)
- fill(field, 0, 0)
- print()
- print(fieldstr(field))
- print()
- print(count(field, xgrid, ygrid))
- def readlines(file_path):
- with open(file_path, 'r') as file:
- lines = [line.strip() for line in file.readlines()]
- return [x for x in lines if x]
- if __name__ == '__main__':
- if len(sys.argv) >= 2:
- lines = readlines(sys.argv[1])
- else:
- lines = []
- advent_day18_part1(lines)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement