summaryrefslogtreecommitdiff
path: root/day7/day7.py
blob: 1eb6c574def4b4480e6db4747595b5a5f001f9dc (plain)
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
"""Day 7."""
import re
from collections import defaultdict

pattern = r"(\d+) ([a-z]+) ([a-z]+) (bag[s]?)"
prog = re.compile(pattern)

with open("input") as f:
    sections = f.read().rstrip().split("\n")

mapping = defaultdict(lambda: [])

# Put bags into dict structure
for section in sections:
    parent, child_str = section.split(" bags contain ")
    children = []
    if "no other bags" not in child_str:
        for child in child_str.replace(".", "").split(", "):
            _, adjective, color, _ = prog.match(child).groups()
            children.append(f"{adjective} {color}")
    for child in children:
        mapping[child].append(parent)

# Part 1
bags = set(mapping['shiny gold'])
while True:
    new_bags = bags.copy()
    for bag in bags:
        for new_bag in mapping[bag]:
            new_bags.add(new_bag)
    if len(new_bags) == len(bags):
        print(len(bags))
        break
    else:
        bags = new_bags


mapping = dict()

# Put bags into dict structure
for section in sections:
    parent, child_str = section.split(" bags contain ")
    children = []
    if "no other bags" not in child_str:
        for child in child_str.replace(".", "").split(", "):
            count, adjective, color, _ = prog.match(child).groups()
            for x in range(int(count)):
                children.append(f"{adjective} {color}")
    if parent not in mapping:
        mapping[parent] = []
    for child in children:
        mapping[parent].append(child)

bags = list(mapping['shiny gold'])
count = 0
new_bags = []
while True:
    new_bags = []
    for x in bags:
        count += 1
        if mapping[x] == []:
            continue
        else:
            new_bags.extend(mapping[x])
    bags = new_bags
    if new_bags == []:
        print(count)
        break