summaryrefslogtreecommitdiffstats
path: root/2020/day7/haversacks.py
diff options
context:
space:
mode:
authorYigit Sever2021-12-12 01:24:32 +0300
committerYigit Sever2021-12-12 01:24:32 +0300
commit4bb6f8d06c0e384f3394012b1d48da58ed28cc5e (patch)
treed6478c85c0488a1059567ccd2882cb10039c2546 /2020/day7/haversacks.py
parentae3853b6e8ab02023ccd74baac6dc177b1ee879a (diff)
downloadaoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.tar.gz
aoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.tar.bz2
aoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.zip
2020, tracking
Diffstat (limited to '2020/day7/haversacks.py')
-rw-r--r--2020/day7/haversacks.py35
1 files changed, 35 insertions, 0 deletions
diff --git a/2020/day7/haversacks.py b/2020/day7/haversacks.py
new file mode 100644
index 0000000..4f7292d
--- /dev/null
+++ b/2020/day7/haversacks.py
@@ -0,0 +1,35 @@
1import networkx as nx
2import re
3
4bagtree = nx.DiGraph()
5bagremover = re.compile(r" bags?\.?$")
6numremover = re.compile(r"^\d+ ")
7
8with open("input", "r") as baglines:
9 for line in baglines:
10 (miniroot, child_str) = list(map(str.strip, line.split("contain")))
11
12 miniroot = miniroot.replace(" bags", "")
13
14 children = list(
15 map(
16 lambda b: re.sub(numremover, "", b),
17 list(
18 map(
19 lambda a: re.sub(bagremover, "", a),
20 list(map(str.strip, child_str.split(","))),
21 )
22 ),
23 )
24 )
25
26 if "no other" in children:
27 continue
28
29 for kid in children:
30 bagtree.add_edge(kid, miniroot)
31
32lengths = dict(nx.all_pairs_shortest_path(bagtree))
33
34# we don't count the shiny gold itself
35print(len(lengths["shiny gold"]) - 1)