/ domm

I hack Perl for fun and profit

Follow me on twitter!
Atom Icom ... on Atom!
<<<<<<<<<<
04.12.2020: Advent of Code Day 3 - the first modulo
03.12.2020: Advent of Code Day 2 - counting regex

Part 1

Again rather simple task, simple solution. I've seen the regex to parse the input in a lot of solutions in various languages - it's nice that even though the languages look rather different, regex unites them all (in a very weird way :-)

my $valid;
while ( my $line = <STDIN> ) {
    chomp($line);
    my ( $min, $max, $letter, $pwd ) = $line =~ /^(\d+)-(\d+) (\w): (\w+)$/;
    my $cnt =()= $pwd =~ /$letter/g;

    $valid++ if ( $min <= $cnt && $cnt <= $max );
}
say $valid;

One thing of interest is the "Saturn" operator =()=, which (using some fancy list/scalar contexts) gets the number of times the regex matches (and thus counts how often the letter occurs in the password)

Oh, and wait a minute: Since Perl 5.32 (released a few months ago) we can finally say (via chained comparisons capability )

   $valid++ if ( $min <= $cnt <= $max );

Part 2

Also not hard, but I tripped over my variable names: I copied the Part-1 solution to a new file, and kept the $min and $max names. And because I wasn't reading the spec properly, I thought we have to count how often the letter occurs in the range defined by min and max. So I got a wrong result and lost a few minutes...

my $valid;
while ( my $line = <STDIN> ) {
    chomp($line);
    my ( $p1, $p2, $letter, $pwd ) = $line =~ /^(\d+)-(\d+) (\w): (\w+)$/;
    my @pwd = ( 'X', split( //, $pwd ) );

    my $hit = 0;
    for my $i ( $p1, $p2 ) {
        $hit++ if $pwd[$i] eq $letter;
    }
    $valid++ if $hit == 1;
}
say $valid;

Instead of fiddling with the array index $i I just padded the array with an extra value, so I could use the provided values as-is.

Oh, and here's my bug:

   for my $i ( $min .. $max ) {
        $hit++ if $pwd[$i] eq $letter;
    }

Note the .. between $min and $max. That's why I renamed the vars to $p1 and $p2.

Stats & Links

Comments (via senph)

03.12.2020: Advent of Code Day 1 - brute loops
29.11.2020: My Advent of Code 2019
28.06.2020: Perl Conference in the Cloud report
18.06.2020: How to reclaim disk space used by docker (volumes), but keep a few important ones
29.03.2020: Perl Virtual Events?
29.03.2020: A very late German Perl Workshop 2020 report
04.03.2020: Perl Intro Curriculum
01.03.2020: YEF: shutdown -h
>>>>>>>>>>
<