diff options
author | Andinus <andinus@nand.sh> | 2020-12-04 19:06:44 +0530 |
---|---|---|
committer | Andinus <andinus@nand.sh> | 2020-12-04 19:06:44 +0530 |
commit | f2da3d2696546d1b12e9eb6a30bab31fefbba4ee (patch) | |
tree | 714a3126d44c84c7f40de901549eb62503a102f3 /2020/day-02/day-02.raku | |
parent | cf9103e808531eb90b9a22668e655290732679d0 (diff) | |
download | aoc-f2da3d2696546d1b12e9eb6a30bab31fefbba4ee.tar.gz |
Add day-02 solution
Diffstat (limited to '2020/day-02/day-02.raku')
-rwxr-xr-x | 2020/day-02/day-02.raku | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/2020/day-02/day-02.raku b/2020/day-02/day-02.raku new file mode 100755 index 0000000..305248a --- /dev/null +++ b/2020/day-02/day-02.raku @@ -0,0 +1,42 @@ +#!/usr/bin/env raku + +# Password grammar was taken from tyil's solution. +grammar Password { + rule TOP { <num> '-' <num> <letter> ':' <password> } + token num { \d+ } + token letter { \w } + token password { \w+ } +} + +sub MAIN ( + # Part to run. + Int $part where * == 1|2 = 1 +) { + my $valid_passwords = 0; + + for "input".IO.lines -> $entry { + if Password.parse($entry) -> $match { + if $part == 1 { + my %chars; + $match<password>.comb.map({ %chars{$_}++ }); + + # Check if the letter exists in the password. + next unless %chars{$match<letter>}; + + # Check for length. + next unless $match<num>[0].Int <= %chars{$match<letter>}; + next unless %chars{$match<letter>} <= $match<num>[1].Int; + } elsif $part == 2 { + my $combed = $match<password>.comb; + my $first = $match<num>[0].Int - 1; + my $second = $match<num>[1].Int - 1; + + next if $combed[$first] eq $combed[$second]; + next unless $combed[$first] eq $match<letter> || $combed[$second] eq $match<letter>; + } + # All checks were completed & this is a valid password. + $valid_passwords++; + } + } + say "Part $part: " ~ $valid_passwords; +} |