summaryrefslogtreecommitdiffstats
path: root/20/py/d08.py
blob: c53a6ffd8c9e88b209b8a37411a87dbfd3ba892c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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))