aoc-2021/05_day/code.py

82 lines
1.6 KiB
Python
Raw Permalink Normal View History

2021-12-05 15:52:20 +00:00
import fileinput
import pprint
def print_diagram(d):
for r in d:
for e in r:
print('.' if e == 0 else e, end='')
print('')
def parse_lines():
lines, points = [], []
for inp in fileinput.input():
val = inp.strip()
if val == '': continue
if val != '':
# quick and dirty way to parse each line (unreadable!)
a, b = list(
map(lambda pt: tuple(list(
map(int, pt.split(','))
)), val.split(' -> '))
)
points.append(a)
points.append(b)
lines.append((a, b))
return lines, points
def draw_line(diagram, a, b, mode):
step = 0
if mode == 'horizontal':
for i in range(a[0], b[0]+1):
diagram[a[1]][i] += 1
step += 1
if mode == 'vertical':
for i in range(a[1], b[1]+1):
diagram[i][a[0]] += 1
step += 1
if mode == 'diagonal':
inc = 1 if b[1] > a[1] else -1
for i in range(a[0], b[0]+1):
x, y = i, a[1]+inc*step
diagram[y][x] += 1
step += 1
return step
def count_overlap(diagram):
c = 0
for r in diagram:
for e in r:
if e >= 2: c += 1
return c
def main():
lines, points = parse_lines()
#print(points)
xs = [x for x,y in points]
ys = [y for x,y in points]
rows = max(ys)+1
columns = max(xs)+1
# create the diagram
diagram = [[0 for j in range(columns)] for i in range(rows)]
# draw lines in diagram
for a,b in lines:
mode = 'diagonal'
if a[1] == b[1]:
mode = 'horizontal'
if a[0] == b[0]:
mode = 'vertical'
if draw_line(diagram, a, b, mode) == 0:
draw_line(diagram, b, a, mode)
#print_diagram(diagram)
overlap = count_overlap(diagram)
print(overlap)
main()