diff options
| author | Gustav Sörnäs <gustav@sornas.net> | 2020-12-08 06:21:20 +0100 |
|---|---|---|
| committer | Gustav Sörnäs <gustav@sornas.net> | 2020-12-08 06:27:21 +0100 |
| commit | f2301c17e9dbc1a4aeda6821f6e518f5c5e29cc5 (patch) | |
| tree | 2af4a2242f1486ede031cdb7ffbdb3911b7f049b | |
| parent | c9cc3b96b3c85cdd118c01b74a8cee554b0dd7e9 (diff) | |
| download | aoc-f2301c17e9dbc1a4aeda6821f6e518f5c5e29cc5.tar.gz | |
day 8
| -rw-r--r-- | 20/py/d08.py | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/20/py/d08.py b/20/py/d08.py new file mode 100644 index 0000000..c53a6ff --- /dev/null +++ b/20/py/d08.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +import sys + + +def pt1(_in): + acc = 0 + loc = 0 + execed = set() + while True: + if loc in execed: + return acc + execed.add(loc) + inst, offset = _in[loc][:-1].split() # \n + offset = int(offset) + if inst == "acc": + acc += offset + loc += 1 + elif inst == "jmp": + loc += offset + else: + loc += 1 + + +def pt2(_in): + def run(prog): + acc = 0 + loc = 0 + execed = set() + while loc < len(prog): + if loc in execed: + return False, acc + execed.add(loc) + inst, offset = prog[loc].strip().split() + offset = int(offset) + if inst == "acc": + acc += offset + loc += 1 + elif inst == "jmp": + loc += offset + else: + loc += 1 + return True, acc + + for i in range(len(_in)): + prog = _in.copy() + inst, offset = prog[i].strip().split() + if inst == "jmp": + prog[i] = "nop 0" + elif inst == "nop": + prog[i] = f"jmp {offset}" + else: + continue + ret, acc = run(prog) + if ret: + return acc + + +if __name__ == "__main__": + if len(sys.argv) > 1: + input = open(sys.argv[1], "r").readlines() + else: + input = open("../input/08", "r").readlines() + print(pt1(input)) + print(pt2(input)) |
