Advent of Code - Day 7: Handy Haversacks#

Part One#

You land at the regional airport in time for your next flight. In fact, it looks like you’ll even have time to grab some food: all flights are currently delayed due to issues in luggage processing.

Due to recent aviation regulations, many rules (your puzzle input) are being enforced about bags and their contents; bags must be color-coded and must contain specific quantities of other color-coded bags. Apparently, nobody responsible for these regulations considered how long they would take to enforce!

For example, consider the following rules:

  • light red bags contain 1 bright white bag, 2 muted yellow bags.

  • dark orange bags contain 3 bright white bags, 4 muted yellow bags.

  • bright white bags contain 1 shiny gold bag.

  • muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.

  • shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.

  • dark olive bags contain 3 faded blue bags, 4 dotted black bags.

  • vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.

  • faded blue bags contain no other bags.

  • dotted black bags contain no other bags.

These rules specify the required contents for 9 bag types. In this example, every faded blue bag is empty, every vibrant plum bag contains 11 bags (5 faded blue and 6 dotted black), and so on.

You have a shiny gold bag. If you wanted to carry it in at least one other bag, how many different bag colors would be valid for the outermost bag? (In other words: how many colors can, eventually, contain at least one shiny gold bag?)

In the above rules, the following options would be available to you:

  • A bright white bag, which can hold your shiny gold bag directly.

  • A muted yellow bag, which can hold your shiny gold bag directly, plus some other bags.

  • A dark orange bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag.

  • A light red bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag.

So, in this example, the number of bag colors that can eventually contain at least one shiny gold bag is 4.

How many bag colors can eventually contain at least one shiny gold bag? (The list of rules is quite long; make sure you get all of it.)

Load and Clean Input data#

Note

The input data can be found here. :::

with open("../../data/advent-of-code/2020/day-7-input") as fid:
    data = fid.readlines()
    data = [x.strip() for x in data]

print(len(data))
print(data[0:2])
594
['light salmon bags contain 5 dotted olive bags, 4 wavy lavender bags.', 'dark purple bags contain 5 striped maroon bags, 1 wavy maroon bag.']
def parse_rule(rule):
    """Parse rule and create a clean data structure for holding information about each rule.

    Parameters
    ----------
    rule: str
        A string corresponding to a given rule for a particular color bag

    Returns
    -------
    dict

    """

    def clean_func(item, split_on=" "):
        return item.strip().split(split_on)

    if "contains" in rule:
        split_on = "contains"
    else:
        split_on = "contain"

    x = clean_func(rule, split_on)

    key = " ".join(clean_func(x[0])[:-1])
    items = clean_func(x[-1], ",")
    clean_items = {}
    for item in items:
        clean_item = clean_func(item)
        if clean_item[0] == "no":
            pass
        else:
            count = int(clean_item[0])
            name = " ".join(clean_item[1:3])

            clean_items[name] = count

    return (key, clean_items)
print(data[0])
print(parse_rule(data[0]))
light salmon bags contain 5 dotted olive bags, 4 wavy lavender bags.
('light salmon', {'dotted olive': 5, 'wavy lavender': 4})
print(data[-1])
print(parse_rule(data[-1]))
vibrant magenta bags contain 2 dark lime bags.
('vibrant magenta', {'dark lime': 2})
clean_data = dict([parse_rule(rule) for rule in data])
test_data = """
light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.
""".strip().split(
    "\n"
)

clean_test_data = dict([parse_rule(rule) for rule in test_data])
clean_test_data
{'light red': {'bright white': 1, 'muted yellow': 2},
 'dark orange': {'bright white': 3, 'muted yellow': 4},
 'bright white': {'shiny gold': 1},
 'muted yellow': {'shiny gold': 2, 'faded blue': 9},
 'shiny gold': {'dark olive': 1, 'vibrant plum': 2},
 'dark olive': {'faded blue': 3, 'dotted black': 4},
 'vibrant plum': {'faded blue': 5, 'dotted black': 6},
 'faded blue': {},
 'dotted black': {}}

Solution#

def contains(data, color):
    def _helper(color):
        if color == "shiny gold":
            return True

        if not data.get(color):
            return False

        contents = data[color]
        for color in contents:
            if _helper(color):
                return True

    total = 0
    for key in data:
        if key != color and _helper(key):
            total += 1

    return total


contains(clean_test_data, "shiny gold")
4
contains_shiny_gold = contains(clean_data, "shiny gold")
print(f"{contains_shiny_gold} bag colors contain at least one shiny gold bag")
261 bag colors contain at least one shiny gold bag

Part Two#

It’s getting pretty expensive to fly these days - not because of ticket prices, but because of the ridiculous number of bags you need to buy!

Consider again your shiny gold bag and the rules from the above example:

faded blue bags contain 0 other bags.
dotted black bags contain 0 other bags.
vibrant plum bags contain 11 other bags: 5 faded blue bags and 6 dotted black bags.
dark olive bags contain 7 other bags: 3 faded blue bags and 4 dotted black bags.

So, a single shiny gold bag must contain 1 dark olive bag (and the 7 bags within it) plus 2 vibrant plum bags (and the 11 bags within each of those): 1 + 17 + 2 + 211 = 32 bags!

Of course, the actual rules have a small chance of going several levels deeper than this example; be sure to count all of the bags, even if the nesting becomes topologically impractical!

Here’s another example:

  • shiny gold bags contain 2 dark red bags.

  • dark red bags contain 2 dark orange bags.

  • dark orange bags contain 2 dark yellow bags.

  • dark yellow bags contain 2 dark green bags.

  • dark green bags contain 2 dark blue bags.

  • dark blue bags contain 2 dark violet bags.

  • dark violet bags contain no other bags.

In this example, a single shiny gold bag must contain 126 other bags.

How many individual bags are required inside your single shiny gold bag?

Solution#

In part 2, we have to check our bags again. This time, we want to find out, how many bags a shiny gold bag contains. We have to count the bags inside a shiny gold bag and then count the bags inside those bags and then count the bags inside those and then…

def get_bag_count(bags, color):
    total = 0
    contents = bags[color]
    for key, value in contents.items():
        total += value
        p = get_bag_count(bags, key)
        if p is not None:
            total += p * value
    return total

Let’s try this function on a few sample tests:

get_bag_count(clean_test_data, "shiny gold")
32
get_bag_count(
    {
        "shiny gold": {"dark red": 2},
        "dark red": {"dark orange": 2},
        "dark orange": {"dark yellow": 2},
        "dark yellow": {"dark green": 2},
        "dark green": {"dark blue": 2},
        "dark blue": {"dark violet": 2},
        "dark violet": {},
    },
    "shiny gold",
)
126
print(
    f'{get_bag_count(clean_data, "shiny gold")} individual bags are required inside a single shiny gold bag'
)
3765 individual bags are required inside a single shiny gold bag