<jupyter_start><jupyter_text>[Advent of Code 2020: Day 8](https://adventofcode.com/2020/day/8)  \-\-\- Day 8: Handheld Halting \-\-\-Your flight to the major airline hub reaches cruising altitude without incident. While you consider checking the in\-flight menu for one of those drinks that come with a little umbrella, you are interrupted by the kid sitting next to you.Their [handheld game console](https://en.wikipedia.org/wiki/Handheld_game_console) won't turn on! They ask if you can take a look.You narrow the problem down to a strange **infinite loop** in the boot code (your puzzle input) of the device. You should be able to fix it, but first you need to be able to run the code in isolation.The boot code is represented as a text file with one **instruction** per line of text. Each instruction consists of an **operation** (`acc`, `jmp`, or `nop`) and an **argument** (a signed number like `+4` or `-20`).*   `acc` increases or decreases a single global value called the **accumulator** by the value given in the argument. For example, `acc +7` would increase the accumulator by 7. The accumulator starts at `0`. After an `acc` instruction, the instruction immediately below it is executed next.*   `jmp` **jumps** to a new instruction relative to itself. The next instruction to execute is found using the argument as an **offset** from the `jmp` instruction; for example, `jmp +2` would skip the next instruction, `jmp +1` would continue to the instruction immediately below it, and `jmp -20` would cause the instruction 20 lines above to be executed next.*   `nop` stands for **No OPeration** \- it does nothing. The instruction immediately below it is executed next.For example, consider the following program:```nop +0acc +1jmp +4acc +3jmp -3acc -99acc +1jmp -4acc +6```These instructions are visited in this order:```nop +0  | 1acc +1  | 2, 8(!)jmp +4  | 3acc +3  | 6jmp -3  | 7acc -99 |acc +1  | 4jmp -4  | 5acc +6  |```First, the `nop +0` does nothing. Then, the accumulator is increased from 0 to 1 (`acc +1`) and `jmp +4` sets the next instruction to the other `acc +1` near the bottom. After it increases the accumulator from 1 to 2, `jmp -4` executes, setting the next instruction to the only `acc +3`. It sets the accumulator to 5, and `jmp -3` causes the program to continue back at the first `acc +1`.This is an **infinite loop**: with this sequence of jumps, the program will run forever. The moment the program tries to run any instruction a second time, you know it will never terminate.Immediately **before** the program would run an instruction a second time, the value in the accumulator is **`5`**.Run your copy of the boot code. Immediately before any instruction is executed a second time, **what value is in the accumulator?**<jupyter_code>import re
import unittest
from IPython.display import Markdown, display

from aoc_puzzle import AocPuzzle

class GameConsole(AocPuzzle):
    
    OP_ACC = 'acc'
    OP_JUMP = 'jmp'
    OP_NOOP = 'nop'
    
    START_ADDR = 0
    
    memory = []
    initial_memory = []
    exec_history = []
    watchdog = 1
    debug = False
    
    def parse_data(self, raw_data):        
        self.initial_memory = raw_data.split('\n')
        self.reset()            
        
    def reset(self):
        if self.memory:
            del self.memory[:]
        self.memory = self.initial_memory.copy()
        
        if self.exec_history:
            del self.exec_history[:]
        self.exec_history = []
        
        self.instruction_ptr = self.START_ADDR
        self.accumulator = 0          
        
    def parse_operation(self):
        m = re.match('(\w{3})\s([\+\-]\d+)', self.memory[self.instruction_ptr])
        op = m.group(1)
        val = int(m.group(2))
        return op, val

    def run(self, output=False):
        
        return_val = 0
        
        while self.instruction_ptr < len(self.memory):
            
            op, val = self.parse_operation()
            
            if self.watchdog > 0:
                if self.instruction_ptr in self.exec_history:
                    if self.debug:
                        print(f'Watchdog: stopped repeat operation {self.instruction_ptr, (op, val)}')
                        print(f'Exec History: {self.exec_history}')
                    return_val = 1
                    break
            
            if self.debug:
                print(self.instruction_ptr, (op, val))

            self.exec_history.append(self.instruction_ptr)
            
            if op != self.OP_JUMP:
                self.instruction_ptr += 1

            if op == self.OP_NOOP:
                pass

            elif op == self.OP_ACC:
                self.accumulator += val

            elif op == self.OP_JUMP:
                self.instruction_ptr += val

            else:
                raise Exception(f'Unknown operation {op} at addr {self.instruction_ptr}.')
                self.reset()
                return 2
                
        if output:
            display(Markdown(f'### Accumulator is `{self.accumulator}`'))
                
        return return_val


class TestBasic(unittest.TestCase):
    
    def test_parse_data(self):
        in_data = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6"
        exp_out = ['nop +0','acc +1','jmp +4','acc +3','jmp -3','acc -99','acc +1','jmp -4','acc +6']
        hgc = GameConsole(in_data)
        self.assertEqual(hgc.memory, exp_out)
            
    def test_intcode_handler(self):
        in_data = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6"
        exp_out = 5
        hgc = GameConsole(in_data)
        hgc.debug = True
        hgc.run()
        self.assertEqual(hgc.accumulator, exp_out)
            
unittest.main(argv=[""], exit=False)
hgc = GameConsole("input/d08.txt")
hgc.run(output=True)<jupyter_output><empty_output><jupyter_text>\-\-\- Part Two \-\-\-After some careful analysis, you believe that **exactly one instruction is corrupted**.Somewhere in the program, **either** a `jmp` is supposed to be a `nop`, **or** a `nop` is supposed to be a `jmp`. (No `acc` instructions were harmed in the corruption of this boot code.)The program is supposed to terminate by **attempting to execute an instruction immediately after the last instruction in the file**. By changing exactly one `jmp` or `nop`, you can repair the boot code and make it terminate correctly.For example, consider the same program from above:```nop +0acc +1jmp +4acc +3jmp -3acc -99acc +1jmp -4acc +6```If you change the first instruction from `nop +0` to `jmp +0`, it would create a single\-instruction infinite loop, never leaving that instruction. If you change almost any of the `jmp` instructions, the program will still eventually find another `jmp` instruction and loop forever.However, if you change the second\-to\-last instruction (from `jmp -4` to `nop -4`), the program terminates! The instructions are visited in this order:```nop +0  | 1acc +1  | 2jmp +4  | 3acc +3  |jmp -3  |acc -99 |acc +1  | 4nop -4  | 5 <--acc +6  | 6```After the last instruction (`acc +6`), the program terminates by attempting to run the instruction below the last instruction in the file. With this change, after the program terminates, the accumulator contains the value **`8`** (`acc +1`, `acc +1`, `acc +6`).Fix the program so that it terminates normally by changing exactly one `jmp` (to `nop`) or `nop` (to `jmp`). **What is the value of the accumulator after the program terminates?**<jupyter_code>class GameConsoleAutorepair(AocPuzzle):
    
    def parse_data(self, raw_data):
        self.hgc = GameConsole(raw_data)
    
    def run(self, output=False):
        
        self.hgc.watchdog = 1
        
        for index, op in enumerate(self.hgc.initial_memory):
            self.hgc.reset()
            self.hgc.memory[index] = self.hgc.memory[index].replace('jmp','nop')
            # If no change was made try switching it the other way
            if self.hgc.memory[index] == self.hgc.initial_memory[index]:
                self.hgc.memory[index] = self.hgc.memory[index].replace('nop','jmp')
            
            if self.hgc.run() == 0:
                if output:
                    display(Markdown(f'### Accumulator is `{self.hgc.accumulator}` after normal program termination.'))
                return self.hgc.accumulator
            
        return -1


class TestBasic(unittest.TestCase):
    
    def test_GameConsoleAutorepair(self):
        in_data = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6"
        exp_out = 8
        gca = GameConsoleAutorepair(in_data)
        #gca.hgc.debug = True
        self.assertEqual(gca.run(), exp_out)
        
unittest.main(argv=[""], exit=False)
gca = GameConsoleAutorepair("input/d08.txt")
gca.run(output=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10944375493625183, 'fraction_numerical': 0.018052578133814737, 'mean_word_length': 2.5828617623282133, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 10, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '256850', 'license': 'MIT', 'n_tokens_mistral': 2777, 'n_tokens_neox': 2596, 'n_words': 970, 'path': 'AoC 2020/AoC 2020 - Day 08.ipynb', 'repo_name': 'RubenFixit/AoC', 'size': '8863'}