~schnouki/advent-of-code

c6c9cfe6b689a774903b52d52046dc462de6381d — Thomas Jost 2 months ago 5b81720
Add brute-force solution for day 8 part 2
2 files changed, 26 insertions(+), 1 deletions(-)

M 2020/day07.py
M 2020/day08.py
M 2020/day07.py => 2020/day07.py +1 -1
@@ 1,6 1,6 @@
#!/usr/bin/env python3

from typing import Dict, List, Tuple
from typing import Dict, Tuple

from aoc import Puzzle, run


M 2020/day08.py => 2020/day08.py +25 -0
@@ 163,6 163,31 @@ acc +6"""

        return vm.acc

    def run_part2_bruteforce(self, data):
        visited_ips = set()

        def detect_loop(vm):
            if vm.ip in visited_ips:
                vm.stopped = True
            else:
                visited_ips.add(vm.ip)

        for pos in range(len(data.ops)):
            op, arg = data.ops[pos]
            if op not in ("nop", "jmp"):
                continue

            vm = data.clone()
            visited_ips.clear()
            new_op = "jmp" if op == "nop" else "nop"
            vm.ops[pos] = (new_op, arg)
            vm.callback = detect_loop
            vm.run()

            if not vm.stopped:
                # Program ran without being interrupted!
                return vm.acc


if __name__ == "__main__":
    run(obj=Day08())