advent-of-code/2024/python/day03.py

52 lines
1.1 KiB
Python
Raw Permalink Normal View History

2024-12-04 02:12:34 +00:00
import shared
import re
from scanf import scanf
2024-12-04 15:19:43 +00:00
2024-12-04 02:12:34 +00:00
# @shared.profile
def part1(rows):
total = 0
2024-12-04 15:19:43 +00:00
r = re.compile(r"mul\(\d+,\d+\)")
2024-12-04 02:12:34 +00:00
for row in rows:
muls = r.findall(row)
for m in muls:
x, y = scanf("mul(%d,%d)", m)
total += x * y
print(total)
# @shared.profile
def part2(rows):
2024-12-04 02:24:00 +00:00
total = 0
2024-12-04 15:19:43 +00:00
r = re.compile(r"(mul\(\d+,\d+\)|do\(\)|don\'t\(\))")
2024-12-04 02:24:00 +00:00
enabled = True
for row in rows:
muls = r.findall(row)
for m in muls:
if m == "don't()":
enabled = False
continue
if m == "do()":
enabled = True
continue
if enabled:
x, y = scanf("mul(%d,%d)", m)
total += x * y
print(total)
2024-12-04 02:12:34 +00:00
def main():
rows = [row for row in shared.load_rows(3)]
with shared.elapsed_timer() as elapsed:
part1(rows)
print("🕒", elapsed())
rows = [row for row in shared.load_rows(3, True)]
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()