Advent of Code 2020 Day 7/25 in the Raku programming language

Let’l look at Day 7 of this year’s Advent of Code. This day’s problem is about handling luggage at the airport. There are some rules like these:

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.

As you see, the rules dictate how you can put bags into other bags. The only characteristics of the bag is its colour. For example, if the bag is dark orange, it can only contain up to 3 bright white bags and up to 4 muted yellow bags.

The first part of the problem is to count the colours of those bag that can contain shiny gold bags (at any level of depth).

My Raku solution is shown below:

my @rules = 'input.txt'.IO.lines;

my %rules;
for @rules -> $rule {
    $rule ~~ m:g/ \w+ ' ' \w+ <?before ' bag'> /;
    my @colours = $/.map: *.Str;
    # say "@colours[0] <- {@colours[1..*].join(', ')}";

    for @colours[1..*] -> $inner {
        next if $inner eq 'no other';
        %rules{$inner}{@colours[0]} = 1;

my %final;
unroll('shiny gold');
# say %final.keys.join(',');
say %final.keys.elems;

sub unroll($current) {
    my $outer = %rules{$current};
    next unless $outer;

    for $outer.keys -> $container {
        # say "'$current' can be found in $container";
        next if %final{$container};

        # say "\tDid not see $container yet";
        %final{$container} = 1;

In this solution, I first build an inverted index %rules of colour relations, and then recursively call the unroll function to reveal the possible chains of nested bag placement.

The second task is to think of the rules as of must-follow instructions (so, each dark orange bag must contain three bright white bags and four muted yellow bags. You need to determine how many bags you have to put inside a shiny gold bag.

Well, I solved the second part of the problem, but the result was not correct. So, I do not post the solution here 🙂 Maybe one day I will add it here.

* * *

→ Browse the code on GitHub
→ See all blog posts on Advent of Code 2020

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code