The task of Day 6 is to count letters :-). Well, not that straightforward. There’s some input like this split into groups and lines:
abc a b c ab ac
We have to count how many times each letter enters in each group. Again, the original task is more storyline-type and you’d better read it in original. I will just show the solution:
say [+] 'input.txt'.IO.slurp.split("\n\n").map: *.lines.join.comb.unique.elems;
Yes, that’s a one-line (I split it in the middle just to make sure it does not break in some unpredictable way).
I read the file as a whole by .slurp
, then split it into groups as .split("\n\n")
. For each group, I join the lines into a single string *.lines.join
and then split into characters and remove the duplicates: .unique
. The number (.elems
) of unique letters is the desired answer for this group. Add them up using a reduction operator [+]
and print.
In the second part of the problem, we only need to take into account the letters that appear in each line of the group. In other words, the number of such letters equals to the number of lines in a group. Hence, the solution:
my @groups = 'input.txt'.IO.slurp.split("\n\n").map: *.lines; say [+] gather for @groups -> $group { my $n = $group.elems; take $group.join.comb.Bag.grep(*.value == $n).elems; }
* * *
→ Browse the code on GitHub
→ See all blog posts on Advent of Code 2020