Advertisement
Guest User

Advent of Code 2020 Day 10

a guest
Dec 10th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. """Day 10 of Advent of Code 2020 Solution"""
  2. from collections import defaultdict
  3.  
  4.  
  5. def adapter_io(file_location) -> list[int]:
  6.     with open(file_location, "r") as f:
  7.         data = [int(line.strip()) for line in f.readlines()]
  8.         data = sorted(data)
  9.         data = [0] + data + [data[-1] + 3]
  10.     return data
  11.  
  12.  
  13. def n_connection_dist(data: list[int]) -> tuple[int, int]:
  14.     adapter_differences = defaultdict(int)
  15.     for i, rating in enumerate(data[1:], 1):
  16.         adapter_differences[rating - data[i - 1]] += 1
  17.     return (adapter_differences[1], adapter_differences[3])
  18.  
  19.  
  20. def part_a(file_location) -> int:
  21.     data = adapter_io(file_location)
  22.     _1, _3 = n_connection_dist(data)
  23.     return _1 * _3
  24.  
  25.  
  26. def part_b(file_location):
  27.     data = adapter_io(file_location)
  28.     graph_nodes = defaultdict(list)
  29.     for i, n in enumerate(data):
  30.         next_actual_nodes = set(data[i+1:i+4])
  31.         next_possible_nodes = set([n + i for i in range(1, 4)])
  32.         for intersecting_node in next_possible_nodes.intersection(next_actual_nodes):
  33.             graph_nodes[n].append(intersecting_node)
  34.  
  35.     n_paths_table = {max(data): 1}
  36.     for node in reversed(data[:-1]):
  37.         n_paths = 0
  38.         for next_node in graph_nodes[node]:
  39.             n_paths += n_paths_table[next_node]
  40.         n_paths_table[node] = n_paths
  41.  
  42.     return n_paths_table[min(data)]
  43.  
  44.  
  45. if __name__ == '__main__':
  46.     file_location = r"data\day10.txt"
  47.     print(part_a(file_location))
  48.     print(part_b(file_location))
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement