Here is my Raku solution to the problem of Day 2 of this year’s Advent of Code.
The problem is to check if the passwords satisfy the requirement which is mentioned before the password:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
The phrase 1-3 a
means that the character a
must appear one to three times in the password, not fewer nor more.
What I do is demonstrated in the following program. The text file is read line by line, and for each of them, I extract the parts using a regex.
Then, the password is transformed into a Bag
object which automatically counts the characters in the string, so we can ask for the number by reading it from the %chars
hash.
my $good = 0; for 'input.txt'.IO.lines() -> $line { $line ~~ / (\d+) '-' (\d+) ' ' (\w) ': ' (\w+) /; my %chars = $/[3].comb.Bag; $good++ if $/[0] <= (%chars{$/[2]} // 0) <= $/[1]; } say $good;
In the second part of the problem, the validity of passwords is defined differently. In the same input file, the numbers in the interval mean the two positions in the password string, only one of which is allowed to contain the given character.
#!/usr/bin/env raku my $good = 0; for 'input.txt'.IO.lines() -> $line { $line ~~ / (\d+) '-' (\d+) ' ' (\w) ': ' (\w+) /; my @chars = $/[3].comb; $good++ if one(@chars[$/[0] - 1], @chars[$/[1] - 1]) eq $/[2]; } say $good;
The first part of the program is the same as before, but the test now includes a so-called one-junction. We demand that only one of the items equals to the character:
one(@chars[$/[0] - 1], @chars[$/[1] - 1]) eq $/[2]
So simple so true.
* * *
→ Browse the code on GitHub
→ See all blog posts on Advent of Code 2020