rosien

Handheld Halting_AOC_2020_Day8

Mar 4th, 2021 (edited)
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. with open('Day8.txt', 'rt') as f:
  2.     data = f.read().split('\n')
  3.  
  4. instructions = {}
  5. for ind, instruction in enumerate(data):
  6.     command, step = instruction.split()
  7.     instructions[ind] = [command, int(step)]
  8.  
  9. def procedure (instructions, key, accumulator):  
  10.     command, step = instructions.get(key)
  11.     if command == 'nop':
  12.         key += 1
  13.     elif command == 'jmp':  
  14.         key += step
  15.     else:
  16.         key += 1
  17.         accumulator += step
  18.     return key, accumulator
  19.  
  20. #Part 1
  21. key = 0
  22. accumulator = 0
  23. keys = list()
  24. # results = {}
  25.  
  26. while True:
  27.     key, accumulator = procedure(instructions, key, accumulator)
  28.     if key not in keys:
  29.         keys.append(key)
  30.     else:
  31.         break
  32. print(accumulator)
  33.  
  34. # Part 2:
  35.  
  36. def search_change(k, instructions):
  37.     dict_change = {'nop': 'jmp', 'jmp': 'nop'}
  38.     instructions_2 = {}
  39.     key_2 = 0
  40.     keys_2 = list()
  41.     accu = 0
  42.     last_key = max(instructions.keys())
  43.     for old_value, new_value in dict_change.items():
  44.         if instructions.get(k)[0] == old_value:
  45.             dict_update={k:[new_value,instructions.get(k)[1]]}
  46.             instructions_2.update(instructions)
  47.             instructions_2.update(dict_update)
  48.             while last_key not in keys_2:
  49.                 key_2, accu = procedure(instructions_2, key_2, accu)
  50.                 if key_2 not in keys_2:
  51.                     keys_2.append(key_2)
  52.                 else:
  53.                     break
  54.             if keys_2[-1] == last_key:
  55.                 key_2, accu = procedure(instructions_2, key_2, accu)
  56.                 print('final_accumulator:', accu)
  57.                 break
  58.  
  59. for k in keys:
  60.     search_change(k, instructions)
Add Comment
Please, Sign In to add comment