Add solution for day 3
This commit is contained in:
parent
b6e50c3949
commit
cc4a0ac15a
1 changed files with 55 additions and 0 deletions
55
src/day03.py
Normal file
55
src/day03.py
Normal file
|
@ -0,0 +1,55 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
from re import finditer
|
||||
from util import print_color, read_input, Color
|
||||
|
||||
|
||||
mul_pattern = "mul\\(([0-9]{1,3},[0-9]{1,3})\\)"
|
||||
do_pattern = "do(n't)?\\(\\)"
|
||||
combined_pattern = f"({mul_pattern}|{do_pattern})"
|
||||
|
||||
|
||||
def part1(input_lines):
|
||||
total = 0
|
||||
for line in input_lines:
|
||||
matches = finditer(mul_pattern, line)
|
||||
for match in matches:
|
||||
(left, right) = map(lambda x: int(x), match.group(1).split(","))
|
||||
total += left * right
|
||||
return total
|
||||
|
||||
|
||||
def part2(input_lines):
|
||||
total = 0
|
||||
enabled = True
|
||||
matches = []
|
||||
for line in input_lines:
|
||||
matches += list(finditer(combined_pattern, line))
|
||||
i = 0
|
||||
while i < len(matches):
|
||||
old_total = total
|
||||
match = matches[i]
|
||||
color = Color.GREY
|
||||
if match.group(0) == "do()":
|
||||
enabled = True
|
||||
elif match.group(0) == "don't()":
|
||||
enabled = False
|
||||
else:
|
||||
color = Color.GREEN if enabled else Color.RED
|
||||
if enabled:
|
||||
(left, right) = map(lambda x: int(x), match.group(2).split(","))
|
||||
total += left * right
|
||||
print_color(f'{i}: {match.group(0)} - {old_total} -> {total}', color)
|
||||
i += 1
|
||||
return total
|
||||
|
||||
|
||||
test_input = read_input("_test")
|
||||
assert 161 == part1(test_input)
|
||||
|
||||
real_input = read_input()
|
||||
print(part1(real_input))
|
||||
|
||||
test_input_2 = read_input("_test_2")
|
||||
assert 48 == part2(test_input_2)
|
||||
print(part2(real_input))
|
Loading…
Reference in a new issue