Advertisement
bob_f

AOC2016D12.py

Oct 27th, 2023
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1.  
  2. from collections import defaultdict
  3.  
  4. def get_puzzle_input(a_file_name: str) -> list[list[str]]:
  5.     with open(a_file_name) as INFILE:
  6.         return [line.split() for line in INFILE if not line.startswith('#')]
  7.  
  8. def solve(a_instructions: list, a_data: defaultdict, a_part=1) -> int:
  9.     next_instruction_index = 0
  10.  
  11.     if a_part == 2:
  12.         a_data['c'] = 1
  13.  
  14.     while next_instruction_index < len(a_instructions):
  15.         next_instruction = a_instructions[next_instruction_index][0]
  16.  
  17.         if next_instruction == 'cpy':
  18.             arg1 = a_instructions[next_instruction_index][1]
  19.             arg2 = a_instructions[next_instruction_index][2]
  20.             a_data[arg2] = int(arg1) if arg1.isdigit() else a_data[arg1]
  21.             next_instruction_index +=1
  22.         elif next_instruction == 'inc':
  23.             arg1 = a_instructions[next_instruction_index][1]
  24.             a_data[arg1] += 1
  25.             next_instruction_index +=1
  26.         elif next_instruction == 'dec':
  27.             arg1 = a_instructions[next_instruction_index][1]
  28.             a_data[arg1] -= 1
  29.             next_instruction_index +=1
  30.         elif next_instruction == 'jnz':
  31.             arg1 = a_instructions[next_instruction_index][1]
  32.             arg2 = a_instructions[next_instruction_index][2]
  33.             arg1_value = int(arg1) if arg1.isdigit() else a_data[arg1]
  34.            
  35.             if arg1_value == 0:
  36.                 next_instruction_index += 1
  37.             else:
  38.                 next_instruction_index+= int(arg2)
  39.         else:
  40.             assert 1 == 0, 'Nah'
  41.  
  42.     return a_data['a']
  43.  
  44. data = defaultdict(int)
  45. instructions = get_puzzle_input('AOC2016\AOC2016D12.txt')
  46.  
  47. print(f'p1: {solve(instructions, data)}')
  48. print(f'p2: {solve(instructions, data, a_part=2)}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement