aboutsummaryrefslogtreecommitdiff
path: root/2020/day2.raku
diff options
context:
space:
mode:
authorMatias Linares <matiaslina@gmail.com>2020-12-05 10:48:05 -0300
committerMatias Linares <matiaslina@gmail.com>2020-12-05 10:48:05 -0300
commit5fa17cd54a1170449a91da48a2fe88a99349daa2 (patch)
tree0391332b9c01645f1c0196ba00e9bcb949495426 /2020/day2.raku
downloadadvent-of-code-5fa17cd54a1170449a91da48a2fe88a99349daa2.tar.gz
Add 2020
Diffstat (limited to '2020/day2.raku')
-rw-r--r--2020/day2.raku67
1 files changed, 67 insertions, 0 deletions
diff --git a/2020/day2.raku b/2020/day2.raku
new file mode 100644
index 0000000..f3952de
--- /dev/null
+++ b/2020/day2.raku
@@ -0,0 +1,67 @@
+use v6;
+
+#use Grammar::Tracer;
+#`{
+1-3 a: abcde
+1-3 b: cdefg
+2-9 c: ccccccccc
+}
+grammar Password {
+ token TOP { <lines>+ }
+ token lines { ^^ <constraints> ' ' <char> ': ' <password> \n }
+ token constraints { $<from> = [ \d+ ] '-' $<to> = [ \d+ ] }
+ token char { \w }
+ token password { <.alnum>+ }
+}
+
+class Part1Actions {
+ method TOP($/) { make $<lines>.grep(*.made.so).elems }
+ method lines($/) { make $<password>.comb($<char>).elems ∈ $<constraints>.made }
+ method constraints($/) { make $<from> .. $<to> }
+}
+
+class Part2Actions {
+ method TOP($/) { make $<lines>.grep(*.made.so).elems }
+ method lines($/) {
+ make
+ $.has-str($<password>.made, $<char>.made, $<constraints><from>.Int)
+ ?^
+ $.has-str($<password>.made, $<char>.made, $<constraints><to>.Int)
+ }
+ method password($/) { make $/.Str }
+ method char($/) { make $/.Str }
+ method has-str(Str $password, Str $char, Int $offset --> Bool) {
+ $password.substr-eq($char, $offset - 1)
+ }
+}
+
+multi sub MAIN('part1', $file) {
+ say Password.parse(slurp($file), actions => Part1Actions.new).made;
+}
+
+multi sub MAIN('part2', $file) {
+ say Password.parse(slurp($file), actions => Part2Actions.new).made;
+}
+
+
+multi sub MAIN('test') {
+ use Test;
+ my $input = q:to/END/;
+ 1-3 a: abcde
+ 1-3 b: cdefg
+ 2-9 c: ccccccccc
+ END
+ subtest 'Part1', {
+ my $g = Password.parse($input, actions => Part1Actions.new);
+ say $g<lines>[0].made;
+
+ is $g.made, 2, 'Example';
+ }
+
+ subtest 'Part2', {
+ my $g = Password.parse($input, actions => Part2Actions.new);
+ say $g<lines>[0].made;
+
+ is $g.made, 1, 'Example';
+ }
+}