Guest User

AOC2020 day8

a guest
Dec 8th, 2020
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. from AoC.Resource import Resource
  2. from AoC import Display
  3. from AoC import Puzzle
  4.  
  5. class Day08(Puzzle.Puzzle):
  6.     instructions = []
  7.  
  8.     def PrepareData(self):
  9.         self.data = self.Resource.SplitLines().Get()
  10.         self.instructions = [(a, int(b)) for a, b in [tuple(x.split()) for x in self.data]]
  11.  
  12.  
  13.     def Run(self, Code):
  14.         def acc(line, acc, param):
  15.             return (line+1, acc+param)
  16.  
  17.         def jmp(line, acc, aparamrg):
  18.             return (line+param, acc)
  19.  
  20.         def nop(line, acc, param):
  21.             return (line+1, acc)
  22.  
  23.         Functions = {"acc": acc, "jmp": jmp, "nop": nop}
  24.  
  25.         Line = 0
  26.         Accumulator = 0
  27.         Executed = []
  28.  
  29.         while Line < len(Code):
  30.             func, param = Code[Line]
  31.             if Line in Executed:
  32.                 break
  33.             Executed.append(Line)
  34.             Line, Accumulator = Functions[func](Line, Accumulator, param)
  35.  
  36.         return (Line == len(Code), Accumulator)
  37.  
  38.    
  39.     def SolvePartOne(self):
  40.         _, Accumulator = self.Run(self.instructions)
  41.         return Accumulator
  42.  
  43.  
  44.     def SolvePartTwo(self):
  45.         for i in range(len(self.instructions)):
  46.             newInstructions = self.instructions.copy()
  47.             func, arg = newInstructions[i]
  48.             if func in ["nop", "jmp"]:
  49.                 func = "nop" if func == "jmp" else "jmp"
  50.                 newInstructions[i] = (func, arg)
  51.                 Completed, Accumulator = self.Run(newInstructions)
  52.  
  53.                 if Completed:
  54.                     return Accumulator
  55.                
  56.  
  57. Display.DisplayAnswers(Day08(Resource(8)))
Advertisement
Add Comment
Please, Sign In to add comment