From 87efe262dda8eb8f6382f7cc7784a77e7c4b3465 Mon Sep 17 00:00:00 2001 From: Andres Date: Sun, 15 Dec 2024 21:22:50 +0100 Subject: [PATCH] 2015 day 6 refactored a bit --- 2015/day-6/part-1.py | 15 +++++---------- 2015/day-6/part-2.py | 33 ++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 21 deletions(-) diff --git a/2015/day-6/part-1.py b/2015/day-6/part-1.py index 8a8620c..33ea6de 100644 --- a/2015/day-6/part-1.py +++ b/2015/day-6/part-1.py @@ -1,15 +1,13 @@ import os import re +from collections import defaultdict file_path = os.path.join(os.path.dirname(__file__), "./input.txt") # file_path = os.path.join(os.path.dirname(__file__), "./test-input.txt") input = open(file_path).read().strip() lines = input.split("\n") -lights = dict() -for i in range(0, 1000): - for j in range(0, 1000): - lights[(i, j)] = 0 +lights = defaultdict(bool) for line in lines: match = re.findall(r"(.*?)(\d*,\d*) through (\d*,\d*)", line) if not match: @@ -21,14 +19,11 @@ for line in lines: for i in range(start[0], end[0] + 1): for j in range(start[1], end[1] + 1): if instruction == "turn on": - lights[(i, j)] += 1 + lights[(i, j)] = True elif instruction == "turn off": - if lights[(i, j)] == 0: - continue - else: - lights[(i, j)] -= 1 + lights[(i, j)] = False else: - lights[(i, j)] += 2 + lights[(i, j)] = not lights[(i, j)] count = 0 for v in lights.values(): count += v diff --git a/2015/day-6/part-2.py b/2015/day-6/part-2.py index 706c653..620780d 100644 --- a/2015/day-6/part-2.py +++ b/2015/day-6/part-2.py @@ -1,3 +1,4 @@ +from collections import defaultdict import os import re @@ -6,17 +7,27 @@ file_path = os.path.join(os.path.dirname(__file__), "./input.txt") input = open(file_path).read().strip() lines = input.split("\n") -count = 0 - +lights = defaultdict(int) for line in lines: - if not any( - [ - len(re.findall(pair, line)) >= 2 - for pair in {line[i] + line[i + 1] for i in range(len(line) - 1)} - ] - ) or not any([line[i + 2] == line[i] for i in range(len(line) - 2)]): + match = re.findall(r"(.*?)(\d*,\d*) through (\d*,\d*)", line) + if not match: continue - - count += 1 - + instruction, start, end = match[0] + instruction = instruction.strip() + start = tuple(map(int, start.split(","))) + end = tuple(map(int, end.split(","))) + for i in range(start[0], end[0] + 1): + for j in range(start[1], end[1] + 1): + if instruction == "turn on": + lights[(i, j)] += 1 + elif instruction == "turn off": + if lights[(i, j)] == 0: + continue + else: + lights[(i, j)] -= 1 + else: + lights[(i, j)] += 2 +count = 0 +for v in lights.values(): + count += v print(count)