-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaoc2020_day10.py
More file actions
69 lines (50 loc) · 1.99 KB
/
Copy pathaoc2020_day10.py
File metadata and controls
69 lines (50 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""
Advent of Code 2020
Day 10: Adapter Array
"""
from collections import Counter
def read_puzzle_input(file_name):
"""read file as list of integers"""
puzzle_input = open(file_name, "r").read().splitlines()
return [int(line) for line in puzzle_input]
def day10_part1(data):
adapters = sorted(data)
adapters.append(adapters[-1] + 3)
diff_count = Counter()
rating = 0
for a in adapters:
diff_count[a - rating] += 1
rating = a
return diff_count[1] * diff_count[3]
def day10_part2(data):
# Sort adapters by joltage; destination is the adapter with highest rating.
adapters = [0] + sorted(data)
dest = adapters[-1]
# Build a graph representing possible connections between adapters.
graph = {}
for i, adapter in enumerate(adapters):
graph[adapter] = [x for x in adapters[i + 1 :] if x - adapter <= 3]
# Coveniently enough, the graph is a DAG in topological order,
# therefore counting paths from each node to last node is O(V+E).
pc = Counter()
pc[dest] = 1
for adapter in reversed(adapters):
for neighbour in graph[adapter]:
pc[adapter] += pc[neighbour]
# The solution is the number of paths from the first node.
return pc[0]
if __name__ == "__main__":
input_data = read_puzzle_input("data/day10.txt")
# Part 1
print("What is the number of 1-jolt differences multiplied by the number of 3-jolt differences?")
print(day10_part1(input_data))
# Part 2
print("What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device?")
print(day10_part2(input_data))
# Test cases
def test_day10_part1():
assert day10_part1([16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4]) == 35
assert day10_part1(read_puzzle_input("data/day10_test.txt")) == 220
def test_day10_part2():
assert day10_part2([16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4]) == 8
assert day10_part2(read_puzzle_input("data/day10_test.txt")) == 19208