advent-of-code/2015/python/day06.py
2022-12-18 23:55:45 -05:00

69 lines
1.6 KiB
Python

import shared
import matrix
import numpy as np
from scanf import scanf
def instruction_parse_p1(mx, inst):
if inst.startswith("turn"):
d, x1,y1, x2,y2 = scanf("turn %s %d,%d through %d,%d", inst)
x2+=1 # inclusive
y2+=1
if d == 'on':
mx[y1:y2,x1:x2] = 1
if d == 'off':
mx[y1:y2,x1:x2] = 0
elif inst.startswith("toggle"):
x1,y1, x2,y2 = scanf("toggle %d,%d through %d,%d", inst)
x2+=1
y2+=1
mx[y1:y2,x1:x2] ^= 1
def instruction_parse_p2(mx, inst):
if inst.startswith("turn"):
d, x1,y1, x2,y2 = scanf("turn %s %d,%d through %d,%d", inst)
if d == 'on':
dx = 1
if d == 'off':
dx = -1
mx[y1:y2+1,x1:x2+1] += dx
mx[mx<0] = 0
elif inst.startswith("toggle"):
x1,y1, x2,y2 = scanf("toggle %d,%d through %d,%d", inst)
dx = 2
mx[y1:y2+1,x1:x2+1] += dx
#mx[mx < 0] = 0
def pt1(instructions):
mx = np.array(matrix.matrix_of_size(1001,1001))
for inst in instructions:
instruction_parse_p1(mx, inst)
print(count(mx))
def pt2(instructions):
mx = np.array(matrix.matrix_of_size(1000,1000))
for inst in instructions:
instruction_parse_p2(mx, inst)
print(_sum(mx))
def count(mx):
flat = np.ravel(mx).tolist()
total = len([x for x in flat if x])
return total
def _sum(mx):
flat = [x for x in np.ravel(mx).tolist() if x]
return sum(flat)
def main():
with open(shared.get_fname(6), "r") as f:
inp = [x.rstrip() for x in f.readlines()]
pt1(inp)
pt2(inp)
print("=17836115")
if __name__ == "__main__":
main()