2021-03-23 06:50:04 +03:00
|
|
|
from collections import deque
|
2021-01-09 07:58:46 +03:00
|
|
|
from fileio import open
|
|
|
|
let lines, descriptions, count
|
|
|
|
|
|
|
|
with open('test/day7.in') as f:
|
|
|
|
lines = [l.strip() for l in f.readlines()]
|
|
|
|
|
|
|
|
descriptions = {}
|
|
|
|
|
|
|
|
for line in lines:
|
2021-01-15 03:53:29 +03:00
|
|
|
let mine, contains = line.split(" bags contain ", 1)
|
2021-01-09 07:58:46 +03:00
|
|
|
if contains[:8] == "no other":
|
|
|
|
descriptions[mine] = []
|
|
|
|
else:
|
2021-03-23 06:50:04 +03:00
|
|
|
let contents = deque()
|
2021-01-09 07:58:46 +03:00
|
|
|
for bag in contains.split(", "):
|
2021-01-15 03:53:29 +03:00
|
|
|
let cnt, rest = bag.split(' ',1)
|
2021-01-09 07:58:46 +03:00
|
|
|
let name = rest.strip().split('bag',1)[0]
|
|
|
|
for i in range(int(cnt)):
|
|
|
|
contents.append(name.strip())
|
|
|
|
descriptions[mine] = contents
|
|
|
|
|
|
|
|
def reaches(bag, target, seen=set()):
|
|
|
|
for n in descriptions[bag]:
|
|
|
|
if n == target:
|
|
|
|
return True
|
|
|
|
if n not in seen:
|
|
|
|
seen.add(n)
|
|
|
|
if reaches(n, target, seen):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
count = 0
|
|
|
|
for bag in descriptions.keys():
|
|
|
|
if reaches(bag, 'shiny gold'):
|
|
|
|
count += 1
|
|
|
|
|
|
|
|
print("There are", count, "bags that can contain a shiny gold bag, eventually.")
|
|
|
|
|
|
|
|
def find_depth(bag):
|
2021-01-10 14:49:01 +03:00
|
|
|
if not descriptions[bag]:
|
2021-01-09 07:58:46 +03:00
|
|
|
return 0
|
|
|
|
let to_scan = descriptions[bag]
|
|
|
|
let count = 0
|
2021-01-10 14:49:01 +03:00
|
|
|
while to_scan:
|
2021-03-23 06:50:04 +03:00
|
|
|
let i = to_scan.popleft()
|
2021-01-09 07:58:46 +03:00
|
|
|
count += 1
|
2021-01-19 16:27:05 +03:00
|
|
|
to_scan.extend(descriptions[i])
|
2021-01-09 07:58:46 +03:00
|
|
|
return count
|
|
|
|
|
|
|
|
print("A shiny gold bag contains", find_depth('shiny gold'), "bags.")
|