DEV Community

Discussion on: AoC Day 5: Alchemical Reduction

Collapse
 
choroba profile image
E. Choroba • Edited

I reached for regular expressions in Perl. I wasn't sure about the performance, but 0.4s for the part 2 seemed enough.

The regex is constructed dynamically and simply lists all the possible pairs to remove.

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $regex = join '|', map { +"$_\u$_", "\u$_$_" } 'a' .. 'z';
                                                  # fix highlighting bug: '
chomp( my $input = <> );

1 while $input =~ s/$regex//g;
say length $input;

For the part 2, I discovered you can start from the already reduced polymer, which improved the performance more than 10 times.

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $regex = join '|', map { +"$_\u$_", "\u$_$_" } 'a' .. 'z';
                                                  # fix highlighting bug: '
chomp( my $input = <> );

1 while $input =~ s/$regex//g;
my $min = length $input;
for my $letter ('a' .. 'z') {
    next unless $input =~ /$letter/i;

    my $removed = $input =~ s/$letter//gri;
    1 while $removed =~ s/$regex//g;
    $min = length $removed if length $removed < $min;
}

say $min;