12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- #!/usr/bin/python3
- import sys
- import re
- # part 1
- def check_special(cycles, reg):
- special = [20, 60, 100, 140, 180, 220]
- for s in special:
- if cycles == s:
- return s * reg
- return 0
- def part1():
- cycles = 0
- reg = 1
- total = 0
- for line in sys.stdin:
- l = line.strip()
- match = None
- if re.match(r'^noop', l):
- cycles += 1
- total += check_special(cycles, reg)
- elif (match := re.match(r'^addx (-?[0-9]+)', l)) is not None:
- value = int(match.groups()[0])
- for i in range(2):
- cycles += 1
- total += check_special(cycles, reg)
- reg += value
- print(f'{total} total')
- # part 2
- def render_crt(crt, reg):
- if crt == 0:
- print()
- print('#' if crt in range(reg - 1, reg + 2) else '.', end='')
- def cycle(cycles, crt, reg):
- render_crt(crt, reg)
- cycles += 1
- crt = (crt + 1) % 40
- return cycles, crt, reg
- def part2():
- cycles = 0
- reg = 1
- crt = 0
- for line in sys.stdin:
- l = line.strip()
- match = None
- if re.match(r'^noop', l):
- cycles, crt, reg = cycle(cycles, crt, reg)
- elif (match := re.match(r'^addx (-?[0-9]+)', l)) is not None:
- value = int(match.groups()[0])
- for i in range(2):
- cycles, crt, reg = cycle(cycles, crt, reg)
- reg += value
- print()
- if sys.argv[1] in '1':
- part1()
- else:
- part2()
|