[Advent of Code 2024](https://adventofcode.com/2024)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. import re
  3. from functools import reduce
  4. from itertools import pairwise
  5. from sys import stdout
  6. # It seems like the goal of the program is just to multiply some numbers.
  7. # It does that with instructions like mul(X,Y), where X and Y are each 1-3
  8. # digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a
  9. # result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
  10. # However, because the program's memory has been corrupted, there are also
  11. # many invalid characters that should be ignored, even if they look like
  12. # part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or
  13. # mul ( 2 , 4 ) do nothing.
  14. # For example, consider the following section of corrupted memory:
  15. # xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
  16. # Adding up the result of each real instruction produces 161
  17. # (2*4 + 5*5 + 11*8 + 8*5).
  18. LOG_FILENAME = "./day03-1.log"
  19. INPUT_FILENAME = "./input03.txt"
  20. logger = logging.Logger(__name__)
  21. formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
  22. sh = logging.StreamHandler(stdout)
  23. sh.setLevel(logging.INFO)
  24. sh.setFormatter(formatter)
  25. fh = logging.FileHandler(LOG_FILENAME, mode="w", encoding="utf-8")
  26. fh.setLevel(logging.DEBUG)
  27. fh.setFormatter(formatter)
  28. logger.addHandler(sh)
  29. logger.addHandler(fh)
  30. def multiply_pair(s):
  31. pair = [int(x) for x in s[4:-1].split(",")]
  32. return reduce(lambda x,y: x*y, pair, 1)
  33. def main():
  34. with open(INPUT_FILENAME, "r") as f:
  35. line = "".join(f.readlines())
  36. MUL_REGEX = r"mul\(\d{1,3},\d{1,3}\)"
  37. matches = re.findall(MUL_REGEX, line)
  38. total_sum = reduce(lambda x,y: x+y, map(multiply_pair, matches))
  39. print(f"Total sum: {total_sum}")
  40. if __name__ == "__main__":
  41. main()