#!/usr/bin/env perl # Day 10 Parts 1 and 2 use strict; use warnings; use v5.22; 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"; foreach my $symbol (split //, $line) { # if the symbol is an opening symbol, add it to the @chunk array if ( $symbol =~ m/\[|\{|\(|\ $symbol; } # if the symbol is a closing symbol... if ( $symbol =~ m/\]|\}|\)|\>/ ) { # ...check if the symbol is a closing symbol for the last opened one if ($closer_for{$symbol} eq $chunk[-1]) { # pop off last opening symbol from the @chunk array pop @chunk; # otherwise, report an error } else { $error_score += $error_score{$symbol}; $state = "corrupted"; last; # go to next line } } } if ($state eq "incomplete") { my $completion_score = 0; foreach (reverse @chunk) { $completion_score = (5 * $completion_score) + $completion_score{$opener_for{$_}}; } push @completion_scores => $completion_score; } } @completion_scores = sort { $a <=> $b } @completion_scores; say "part 1 $error_score"; say "part 2 ", $completion_scores[(scalar @completion_scores) / 2];