/ 10.py
10.py
1 #!/usr/bin/python3 2 3 # run it as 4 # ./10.py inputs/10 [--one | --two] [--debug] 5 6 import sys 7 import logging 8 if '--debug' in sys.argv: 9 logging.basicConfig(level=logging.DEBUG) 10 logger = logging.getLogger() 11 12 def get_commands(): 13 with open(sys.argv[1]) as f: 14 for line in f: 15 line = line.strip().split() 16 if len(line) == 1: 17 yield [line[0],] 18 else: 19 yield [line[0], int(line[1])] 20 21 class Cpu: 22 notable_cycles = (20, 60, 100, 140, 180, 220) 23 24 def __init__(self, commands): 25 self.current_cycle = 0 26 self.register = 1 27 self.input = commands 28 self.current_command = None 29 30 def do_cycle(self): 31 if not self.current_command: 32 self.current_command = next(self.input) 33 out = self.increment_cycle_and_check_noteable() 34 logger.info('cycle {}, running command {}'.format( 35 self.current_cycle, self.current_command)) 36 if self.current_command[0] == 'noop': 37 self.current_command = None 38 elif self.current_command[0] == 'addx': 39 self.current_command[0] = 'addx_progress' 40 elif self.current_command[0] == 'addx_progress': 41 self.register += self.current_command[1] 42 self.current_command = None 43 return out 44 45 def increment_cycle_and_check_noteable(self): 46 self.current_cycle += 1 47 if self.current_cycle in self.notable_cycles: 48 return self.current_cycle * self.register 49 50 # def check_notable(self): 51 # if self.current_cycle in self.notable_cycles: 52 # return self.current_cycle * self.register 53 54 55 if __name__ == '__main__': 56 cpu = Cpu(get_commands()) 57 if '--one' in sys.argv: 58 the_sum = [] 59 while True: 60 try: the_sum.append(cpu.do_cycle()) 61 except StopIteration: break 62 print(sum(filter(None, the_sum))) 63 elif '--two' in sys.argv: 64 display = '' 65 while True: 66 if cpu.register -1 <= cpu.current_cycle % 40 <= cpu.register + 1: 67 display += '#' 68 else: 69 display += '.' 70 try: cpu.do_cycle() 71 except StopIteration: break 72 for line in range(6): 73 print(display[line*40:line*40+40])