solution.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/python3
  2. import sys
  3. import re
  4. # part 1
  5. def check_special(cycles, reg):
  6. special = [20, 60, 100, 140, 180, 220]
  7. for s in special:
  8. if cycles == s:
  9. return s * reg
  10. return 0
  11. def part1():
  12. cycles = 0
  13. reg = 1
  14. total = 0
  15. for line in sys.stdin:
  16. l = line.strip()
  17. match = None
  18. if re.match(r'^noop', l):
  19. cycles += 1
  20. total += check_special(cycles, reg)
  21. elif (match := re.match(r'^addx (-?[0-9]+)', l)) is not None:
  22. value = int(match.groups()[0])
  23. for i in range(2):
  24. cycles += 1
  25. total += check_special(cycles, reg)
  26. reg += value
  27. print(f'{total} total')
  28. # part 2
  29. def render_crt(crt, reg):
  30. if crt == 0:
  31. print()
  32. print('#' if crt in range(reg - 1, reg + 2) else '.', end='')
  33. def cycle(cycles, crt, reg):
  34. render_crt(crt, reg)
  35. cycles += 1
  36. crt = (crt + 1) % 40
  37. return cycles, crt, reg
  38. def part2():
  39. cycles = 0
  40. reg = 1
  41. crt = 0
  42. for line in sys.stdin:
  43. l = line.strip()
  44. match = None
  45. if re.match(r'^noop', l):
  46. cycles, crt, reg = cycle(cycles, crt, reg)
  47. elif (match := re.match(r'^addx (-?[0-9]+)', l)) is not None:
  48. value = int(match.groups()[0])
  49. for i in range(2):
  50. cycles, crt, reg = cycle(cycles, crt, reg)
  51. reg += value
  52. print()
  53. if sys.argv[1] in '1':
  54. part1()
  55. else:
  56. part2()