advent/2018/10.py

69 lines
1.7 KiB
Python
Raw Normal View History

2018-12-11 06:52:29 +00:00
from collections import defaultdict
from itertools import chain
import re
def test(data, threshold):
rows, columns = defaultdict(list), defaultdict(list)
for (x, y), _ in data:
rows[y].append(x)
columns[x].append(y)
for line in chain(rows.values(), columns.values()):
consecutive = []
for point in sorted(line):
try:
prev = consecutive[-1]
if point != prev and point != prev + 1:
consecutive.clear()
except IndexError:
pass
consecutive.append(point)
if len(consecutive) > threshold:
return True
return False
def advance(data):
for i, (point, velocity) in enumerate(data):
new_x = point[0] + velocity[0]
new_y = point[1] + velocity[1]
data[i][0] = (new_x, new_y)
def render(data):
xmin = ymin = float('inf')
xmax = ymax = 0
for (x, y), _ in data:
if x < xmin: xmin = x
if x > xmax: xmax = x
if y < ymin: ymin = y
if y > ymax: ymax = y
rows = ymax - ymin + 1
cols = xmax - xmin + 1
lines = [['.'] * cols for i in range(rows)]
for (x, y), _ in data:
printx, printy = x - xmin, y - ymin
lines[printy][printx] = '#'
print('\n'.join(''.join(line) for line in lines))
with open('data/10.txt') as f:
data = []
# f = pyperclip.paste().split('\r\n')
for line in f:
m = re.match('position=<(.+), (.+)> velocity=<(.+), (.+)>', line)
values = list(map(int, m.groups()))
p, v = values[:2], values[2:]
data.append([p, v])
second = 0
while not test(data, 7):
advance(data)
second += 1
print(f'Second: {second}', end='\r')
print()
render(data)