JonathanGupton

Advent of Code 2024 - Day 03 - Python

Dec 3rd, 2024
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. from pathlib import Path
  2. import re
  3.  
  4.  
  5. def get_data(filepath: Path) -> str:
  6.     with open(filepath, "r") as f:
  7.         data = f.read()
  8.     return data
  9.  
  10.  
  11. def multiply(ops: str) -> int:
  12.     num_pattern = r"mul\((\d*),(\d*)\)"
  13.     results = re.match(num_pattern, ops)
  14.     return int(results.group(1)) * int(results.group(2))
  15.  
  16.  
  17. def parse_and_process_mul(instructions: str) -> int:
  18.     mul_pattern = r"mul\(\d*,\d*\)"
  19.     total = 0
  20.     for val in re.findall(mul_pattern, instructions):
  21.         total += multiply(val)
  22.     return total
  23.  
  24.  
  25. def parse_and_process_with_dos_and_donts(instructions: str) -> int:
  26.     do_check_pattern = r"(mul\(\d*,\d*\))|(do\(\))|(don't\(\))"
  27.     total = 0
  28.     dont_flag = False
  29.     for val in re.findall(do_check_pattern, instructions):
  30.         match val:
  31.             case ("", "do()", ""):
  32.                 if dont_flag:
  33.                     dont_flag = False
  34.             case ("", "", "don't()"):
  35.                 dont_flag = True
  36.             case (ops, "", ""):
  37.                 if dont_flag:
  38.                     continue
  39.                 total += multiply(ops)
  40.     return total
  41.  
  42.  
  43. def part_a_example():
  44.     example1 = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"
  45.     result = parse_and_process_mul(example1)
  46.     print(result)  # 161
  47.  
  48.  
  49. def part_a():
  50.     fp = Path(r"data/day03.txt")
  51.     instructions = get_data(fp)
  52.     result = parse_and_process_mul(instructions)
  53.     print(result)
  54.  
  55.  
  56. def part_b_example():
  57.     example2 = r"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
  58.     result = parse_and_process_with_dos_and_donts(example2)
  59.     print(result)  # 48
  60.  
  61.  
  62. def part_b():
  63.     fp = Path(r"data/day03.txt")
  64.     instructions = get_data(fp)
  65.     result = parse_and_process_with_dos_and_donts(instructions)
  66.     print(result)
  67.  
  68.  
  69. if __name__ == '__main__':
  70.     part_a_example()
  71.     part_a()
  72.     part_b_example()
  73.     part_b()
  74.  
Advertisement
Add Comment
Please, Sign In to add comment