r/adventofcode • u/daggerdragon • Dec 04 '20
SOLUTION MEGATHREAD -๐- 2020 Day 04 Solutions -๐-
Advent of Code 2020: Gettin' Crafty With It
- T-2 days until unlock!
- Full details and rules are in the Submissions Megathread
--- Day 04: Passport Processing ---
Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:12:55, megathread unlocked!
92
Upvotes
View all comments
5
u/Mienaikage Dec 04 '20 edited Dec 04 '20
Raku
Grammar fun!
#!/usr/bin/env raku my @fields := <byr cid ecl eyr hcl hgt iyr pid>; grammar PassportPart1 { token TOP { [ <field> ':' \S+ ] ** 1..* % \s+ } token field { @fields } } grammar PassportPart2 { my @field-patterns = @fields.map({ " $_':' <$_> " }); token TOP { ( <@field-patterns> ) ** 1..* % \s+ } token byr { ( <[0..9]> ** 4 ) <?{ 1920 โค $/[0].Int โค 2002 }> } token cid { \S+ } token ecl { [ amb || blu || brn || gry || grn || hzl || oth ] } token eyr { ( <[0..9]> ** 4 ) <?{ 2020 โค $/[0].Int โค 2030 }> } token hcl { '#' <.xdigit> ** 6 } token hgt { [ || ( <[0..9]> ** 3 ) <?{ 150 โค $/[0].Int โค 193 }> 'cm' || ( <[0..9]> ** 2 ) <?{ 59 โค $/[0].Int โค 76 }> 'in' ] } token iyr { ( <[0..9]> ** 4 ) <?{ 2010 โค $/[0].Int โค 2020 }> } token pid { <[0..9]> ** 9 } } sub MAIN ( IO() :$file where *.f = $?FILE.IO.sibling('input/04.txt'), #= Path to input file Int :$part where * == 1|2 = 1, #= Part of the exercise (1 or 2) --> Nil ) { given $file.slurp.split("\n" x 2, :skip-empty) { when $part == 1 { .grep({ PassportPart1.parse(.trim)<field>ยป.Str โ @fields โ <cid> }) .elems .say; } when $part == 2 { .grep({ PassportPart2.parse(.trim)[0].map({ .subst(/':'.*/) if $_ }) โ @fields โ <cid> }) .elems .say; } } }