Advertisement
bob_f

AOC2020D14.py

Oct 8th, 2024
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1.  
  2. def get_puzzle_input(a_file_name: str) -> list[str]:
  3.     with open(a_file_name) as INFILE:
  4.         return [line.rstrip() for line in INFILE if not line.startswith('#')]
  5.  
  6. def get_masked_decimal(a_mask: str, a_decimal_in: int) -> int:
  7.     masked_decimal: int
  8.     mask_length = len(a_mask)
  9.     in_value_binary = f'{a_decimal_in:0{mask_length}b}'
  10.     out_value_binary = ''.join([v if m == 'X' else m for v, m in zip(in_value_binary, a_mask)])
  11.     masked_decimal = int(out_value_binary, 2)
  12.  
  13.     return masked_decimal
  14.  
  15. def main(a_program: list[str], a_result_map: dict[int, int]) -> None:
  16.     mask: str
  17.     memory_location: int
  18.     value_decimal: int
  19.  
  20.     for program_line in program:
  21.         program_line = program_line.split(' = ')
  22.  
  23.         if program_line[0] == 'mask':
  24.             mask = program_line[1]
  25.             # print(f"{mask=}")
  26.         else:
  27.             memory_location = int(program_line[0].strip('mem[]'))
  28.             value_decimal = int(program_line[1])
  29.             # print(f"{memory_location=}, {value_decimal=}")
  30.            
  31.             result: int = get_masked_decimal(mask, value_decimal)
  32.             # print(f"{result=}")
  33.  
  34.             a_result_map[memory_location] = result
  35.            
  36. program = get_puzzle_input('aoc_2020/aoc_2020_day_14.txt')
  37. # print(f"{program=}")
  38.  
  39. result_map: dict = {}
  40. main(program, result_map)
  41. # print(f"{result_map=}")
  42.  
  43. print(f"p1={sum(v for v in result_map.values())}")
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement