diff --git a/day8/day8.py b/day8/day8.py index 2d5b2da..20ba1d6 100644 --- a/day8/day8.py +++ b/day8/day8.py @@ -1,3 +1,6 @@ +import copy + + def part1(): file = open("input.txt") @@ -30,8 +33,61 @@ def part1(): print("Part 1: %d" % acc) + +def brute(i, instructions): + op = instructions[i]['op'] + if op == 'nop': + instructions[i]['op'] = 'jmp' + elif op == 'jmp': + instructions[i]['op'] = 'nop' + else: + return 0 + + finger = 0 + acc = 0 + + while not instructions[finger]['visited']: + op = instructions[finger]['op'] + arg = instructions[finger]['arg'] + instructions[finger]['visited'] = True + + if op == 'nop': + finger += 1 + continue + elif op == 'jmp': + finger += arg + elif op == 'acc': + acc += arg + finger += 1 + + if instructions[len(instructions) - 1]['visited']: + return acc + + return 0 + + def part2(): - print("Part 2: %d") + file = open("input.txt") + + instructions = [] + + for line in file: + args = line.strip().split(" ") + instructions.append({ + 'op': args[0], + 'arg': int(args[1]), + 'visited': False + }) + + acc = 0 + for i in range(0, len(instructions)): + op = instructions[i]['op'] + if op == 'jmp' or op == 'nop': + acc = brute(i, copy.deepcopy(instructions)) + if acc > 0: + break + + print("Part 2: %d" % acc) if __name__ == "__main__":