"""Day 8.""" with open("input") as f: instructions = f.read().rstrip().split("\n") def parse_instructions(instructions): """Parse Instructions.""" acc = 0 visited = set() loc = 0 for x in range(len(instructions)): try: inst, val = instructions[loc].split(" ") except IndexError: if x == len(instructions): return acc, False else: return acc, True if loc in visited: break else: visited.add(loc) if inst == "jmp": loc += int(val) elif inst == "acc": acc += int(val) loc += 1 elif inst == "nop": loc += 1 successful = x == len(instructions) return acc, successful def instruction_generator(instructions): yield instructions for x, line in enumerate(instructions): inst, val = line.split(" ") if inst == 'nop': new = instructions.copy() new[x] = f"jmp {val}" yield new elif inst == 'jmp': new = instructions.copy() new[x] = f"nop {val}" yield new # Part 1 acc, _ = parse_instructions(instructions) print(acc) # Part 2 for intset in list(instruction_generator(instructions)): acc, successful = parse_instructions(intset) if successful: print(acc)