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

In Day 4 of the Advent of Code, we are checking the fields of the passports. For each passport, there are a few fields labelled with a three-letter codes:

  • byr (Birth Year)
  • iyr (Issue Year)
  • eyr (Expiration Year)
  • hgt (Height)
  • hcl (Hair Color)
  • ecl (Eye Color)
  • pid (Passport ID)
  • cid (Country ID)

The full record for a single passport contains colon-separated pairs key:value:

hgt:180cm ecl:amb eyr:2028 cid:237
pid:334803890 byr:1953 hcl:#18171d

First, you have to make sure that all the passports contain all required fields. The required fields are the first eight of the shown above. The cid field is optional. If one of the required fields is missing, the passport is considered invalid. You need to count the number of valid passports.

my @passports = 'input.txt'.IO.slurp.split("\n\n");

my $valid = 0;
for @passports -> $passport {
    my $fields = ($ *.split(':').first).sort.join;    
    $valid++ if $fields 
        eq one <byrcidecleyrhclhgtiyrpid byrecleyrhclhgtiyrpid>;

say $valid;

In my solution, I am extracting the field names from the passport data and join them together (sorted). In this case, the field names should give one of the strings byrcidecleyrhclhgtiyrpid or byrecleyrhclhgtiyrpid, which I check with the one-junction.

In the second part, the tests are stricter. You not only have to make sure the fields are there, but also to check that the values are correct. Such as years have four digits and fall into some predefined ranges. Let me not paste the whole program here, as it contains a lot of regexes in the checks and is quite wordy in general. You can find my solution on GitHub. Alternatively, try solving this problem with Raku grammars.

* * *

→ 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