aoc2021

Advent of Code 2021 solutions in Perl.
git clone git://git.samirparikh.com/aoc2021
Log | Files | Refs | README

commit 6be072db3d40df7bc79e7d24a6ef2e7879871a2d
parent 89fb0e4d563de933d8944dad2381d544a7bcf1b1
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Thu, 23 Dec 2021 18:56:23 +0000

obtain solutions for both parts 1 and 2 for Day 10 in one program

Diffstat:
Aday10.pl | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 94 insertions(+), 0 deletions(-)

diff --git a/day10.pl b/day10.pl @@ -0,0 +1,94 @@ +#!/usr/bin/env perl + +# Day 10 Part 1 +use strict; +use warnings; +use v5.22; +use Data::Dumper; + +sub get_filehandle { + if (@ARGV !=1) { + die "Usage: $0 [input-filename]"; + } + my $input_filename = $ARGV[0]; + open my $filehandle, '<', $input_filename or + die "Could not open input file $input_filename: $!"; + return $filehandle; +} + +my $filehandle = get_filehandle(); +chomp( my @input = ( <$filehandle> ) ); +my %closer_for = ( + ']' => '[', + '}' => '{', + ')' => '(', + '>' => '<', +); +my %opener_for = ( + '[' => ']', + '{' => '}', + '(' => ')', + '<' => '>', +); +my %error_score = ( + ']' => 57, + '}' => 1197, + ')' => 3, + '>' => 25137, +); +my %completion_score = ( + ']' => 2, + '}' => 3, + ')' => 1, + '>' => 4, +); +my $error_score = 0; +my @completion_scores = (); +foreach my $line (@input) { + my @chunk; + my $state = "incomplete"; + print $line; + foreach my $symbol (split //, $line) { + # if the symbol is an opening symbol, add it to the @chunk array + if ( $symbol =~ m/\[|\{|\(|\</ ) { + push @chunk => $symbol; + #print "$symbol is an opener. "; + #say "current chunk is @chunk"; + } + # if the symbol is a closing symbol... + if ( $symbol =~ m/\]|\}|\)|\>/ ) { + #say "$symbol is a closer"; + # ...check if the symbol is a closing symbol for the last opened one + if ($closer_for{$symbol} eq $chunk[-1]) { + #say "$symbol is a matching closer"; + # pop off last opening symbol from the @chunk array + pop @chunk; + #say "current chunk is @chunk"; + # otherwise, report an error + } else { + #say "Expected $opener_for{$chunk[-1]}, but found $symbol instead."; + $error_score += $error_score{$symbol}; + $state = "corrupted"; + last; # go to next line + } + } + } + #say "\t$state"; + if ($state eq "incomplete") { + my $completion_score = 0; + print "\t$state\t"; + foreach (reverse @chunk) { + print ; + $completion_score = (5 * $completion_score) + + $completion_score{$opener_for{$_}}; + } + print "\n"; + push @completion_scores => $completion_score; + } else { + say "\t$state"; + } +} +@completion_scores = sort { $a <=> $b } @completion_scores; +say "part 1 $error_score"; +#say "part 2 @completion_scores"; +say "part 2 ", $completion_scores[(scalar @completion_scores) / 2];