netsplit's recent activity
-
Comment on Day 1: Secret Entrance in ~comp.advent_of_code
-
Comment on Day 2: Gift Shop in ~comp.advent_of_code
netsplit (edited )LinkHere are my solutions for both parts in Perl using a feature from the relatively newly released v5.42. I always find that I lean a little heavily on regular expressions for my Advent of Code...Here are my solutions for both parts in Perl using a feature from the relatively newly released v5.42. I always find that I lean a little heavily on regular expressions for my Advent of Code solutions.
Part 1 (Perl)
#!/usr/bin/env perl use strict; use warnings; use v5.42.0; use feature 'keyword_all'; no warnings 'experimental::keyword_all'; use File::Slurper 'read_lines'; my @content = read_lines 'input.txt'; my @ranges = split ',', $content[0]; my $total = 0; foreach my $range (@ranges) { my ($start, $end) = split '-', $range; foreach my $id ($start..$end) { my @chars = split //, $id; my $digits = scalar @chars; next if $digits % 2 != 0; my $count = int $digits / 2; my @parts = $id =~ /\d{$count}/g; $total += $id if scalar @parts == 2 && $parts[0] == $parts[1]; } } print "The answer is: ${total}\n";Part 2 (Perl)
#!/usr/bin/env perl use strict; use warnings; use v5.42.0; use feature 'keyword_all'; no warnings 'experimental::keyword_all'; use File::Slurper 'read_lines'; my @content = read_lines 'input.txt'; my @ranges = split ',', $content[0]; my $total = 0; foreach my $range (@ranges) { my ($start, $end) = split '-', $range; ID: foreach my $id ($start..$end) { my @chars = split //, $id; my $digits = scalar @chars; next if $digits < 2; for (my $i = 2; $i <= $digits; ++$i) { next if $digits % $i != 0; my $count = int $digits / $i; my @parts = $id =~ /\d{$count}/g; if (scalar @parts == $i && all { $_ eq $parts[0] } @parts) { $total += $id; next ID; } } } } print "The answer is: ${total}\n";Slightly compacted versions...
Part 1 (Perl)
perl -ne 'for(split/,/){($s,$e)=split/-/;for($s..$e){$t+=$_ if/^(.*)\1$/}}print$t' input.txtPart 2 (Perl)
perl -ne 'for(split/,/){($s,$e)=split/-/;for($s..$e){$t+=$_ if/^(.*)\1+$/}}print$t' input.txt
Here are my slightly brute-forced day 1 solutions in Perl.
Spoiler
I was initially tripped up by the counter resets at 0 and 100, hence the slightly clumsy workaround there.
Part 1 (Perl)
Part 2 (Perl)