#!/usr/bin/env python3
#Advent of Code
#2020 Day 8, Part 1
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):classHGC:def__init__(self,program):self.program=programself.bounds=len(program)self.acc=0self.ip=0self.seen=set()defrun(self):whileself.ipnotinself.seen:self.seen.add(self.ip)self.execute(*self.program[self.ip])defexecute(self,op,arg):ifop=="acc":self.acc+=argself.ip+=1elifop=="jmp":self.ip+=argelifop=="nop":self.ip+=1console=HGC([(line.split()[0],int(line.split()[1]))forlineinpuzzle_input])console.run()returnconsole.accdefmain():puzzle_input=util.read.as_lines()acc=solve(puzzle_input)print("The value in the accumulator before an instruction is executed for a second time is "+str(acc)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve(["nop +0","acc +1","jmp +4","acc +3","jmp -3","acc -99","acc +1","jmp -4","acc +6"]),5)if__name__=="__main__":run(main)
#!/usr/bin/env python3
#Advent of Code
#2020 Day 8, Part 2
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):classHGC:def__init__(self,program,patch_location):self.program=programself.bounds=len(program)self.patch_location=patch_locationself.acc=0self.ip=0self.seen=set()defrun(self):whileself.ipnotinself.seenand0<=self.ip<self.bounds:self.seen.add(self.ip)ifself.ip==self.patch_location:ifself.program[self.ip][0]=="jmp":self.execute("nop",self.program[self.ip][1])else:self.execute("jmp",self.program[self.ip][1])else:self.execute(*self.program[self.ip])returnnot(0<=self.ip<self.bounds)defexecute(self,op,arg):ifop=="acc":self.acc+=argself.ip+=1elifop=="jmp":self.ip+=argelifop=="nop":self.ip+=1program=[(line.split()[0],int(line.split()[1]))forlineinpuzzle_input]# Optimisation based on a conversation with a friend (@DavidDwittyy on Twitter)
# The corrupted operation will be one of those executed in Part 1, so only
# those operations need to be checked.
#
# On my hardware, this reduces the runtime to somewhere in the neighbourhood
# of 3/8 of its original runtime (from about 40ms to about 15ms)
part1=HGC(program,-1)part1.run()foriinlist(part1.seen):ifprogram[i][0]=="acc":continueconsole=HGC(program,i)ifconsole.run():returnconsole.accdefmain():puzzle_input=util.read.as_lines()acc=solve(puzzle_input)print("The value in the accumulator after the program terminates is "+str(acc)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve(["nop +0","acc +1","jmp +4","acc +3","jmp -3","acc -99","acc +1","jmp -4","acc +6"]),8)if__name__=="__main__":run(main)