aoc/2015/day06.py

93 lines
2.6 KiB
Python
Raw Normal View History

2023-05-12 10:28:10 -04:00
#!/usr/bin/env python3
from typing import TextIO
grid: dict[tuple, bool] = {}
newgrid: dict[tuple, int] = {}
def part1(instructions: TextIO) -> int:
for ins in instructions:
ins = ins.strip().split()
# print(ins)
command = ins[0:2]
if len(ins) == 5:
fr = tuple([int(x) for x in ins[2].split(",")])
else:
fr = tuple([int(x) for x in ins[1].split(",")])
to = tuple([int(x) for x in ins[-1].split(",")])
if command == ["turn", "off"]:
for x in range(fr[0], to[0] + 1):
for y in range(fr[1], to[1] + 1):
if (x, y) in grid:
del grid[(x, y)]
elif command == ["turn", "on"]:
for x in range(fr[0], to[0] + 1):
for y in range(fr[1], to[1] + 1):
if (x, y) not in grid:
grid[(x, y)] = True
else: # Toggle
for x in range(fr[0], to[0] + 1):
for y in range(fr[1], to[1] + 1):
if (x, y) not in grid:
grid[(x, y)] = True
else:
del grid[(x, y)]
return len(grid)
def part2(instructions: TextIO) -> int:
for ins in instructions:
ins = ins.strip().split()
command = ins[0:2]
if len(ins) == 5:
fr = tuple([int(x) for x in ins[2].split(",")])
else:
fr = tuple([int(x) for x in ins[1].split(",")])
to = tuple([int(x) for x in ins[-1].split(",")])
if command == ["turn", "off"]:
for x in range(fr[0], to[0] + 1):
for y in range(fr[1], to[1] + 1):
if (x, y) not in newgrid:
newgrid[(x, y)] = 0
elif newgrid[(x, y)] != 0:
newgrid[(x, y)] -= 1
elif command == ["turn", "on"]:
for x in range(fr[0], to[0] + 1):
for y in range(fr[1], to[1] + 1):
if (x, y) not in newgrid:
newgrid[(x, y)] = 1
else:
newgrid[(x, y)] += 1
else: # Toggle
for x in range(fr[0], to[0] + 1):
for y in range(fr[1], to[1] + 1):
if (x, y) not in newgrid:
newgrid[(x, y)] = 2
else:
newgrid[(x, y)] += 2
return sum(newgrid.values())
if __name__ == "__main__":
with open("day06.txt", "r") as f:
print(part1(f))
with open("day06.txt", "r") as f:
print(part2(f))