day10.pl (2140B) - raw
1 #!/usr/bin/env perl 2 3 # Day 10 Parts 1 and 2 4 use strict; 5 use warnings; 6 use v5.22; 7 8 sub get_filehandle { 9 if (@ARGV !=1) { 10 die "Usage: $0 [input-filename]"; 11 } 12 my $input_filename = $ARGV[0]; 13 open my $filehandle, '<', $input_filename or 14 die "Could not open input file $input_filename: $!"; 15 return $filehandle; 16 } 17 18 my $filehandle = get_filehandle(); 19 chomp( my @input = ( <$filehandle> ) ); 20 my %closer_for = ( 21 ']' => '[', 22 '}' => '{', 23 ')' => '(', 24 '>' => '<', 25 ); 26 my %opener_for = ( 27 '[' => ']', 28 '{' => '}', 29 '(' => ')', 30 '<' => '>', 31 ); 32 my %error_score = ( 33 ']' => 57, 34 '}' => 1197, 35 ')' => 3, 36 '>' => 25137, 37 ); 38 my %completion_score = ( 39 ']' => 2, 40 '}' => 3, 41 ')' => 1, 42 '>' => 4, 43 ); 44 my $error_score = 0; 45 my @completion_scores = (); 46 foreach my $line (@input) { 47 my @chunk; 48 my $state = "incomplete"; 49 foreach my $symbol (split //, $line) { 50 # if the symbol is an opening symbol, add it to the @chunk array 51 if ( $symbol =~ m/\[|\{|\(|\</ ) { 52 push @chunk => $symbol; 53 } 54 # if the symbol is a closing symbol... 55 if ( $symbol =~ m/\]|\}|\)|\>/ ) { 56 # ...check if the symbol is a closing symbol for the last opened one 57 if ($closer_for{$symbol} eq $chunk[-1]) { 58 # pop off last opening symbol from the @chunk array 59 pop @chunk; 60 # otherwise, report an error 61 } else { 62 $error_score += $error_score{$symbol}; 63 $state = "corrupted"; 64 last; # go to next line 65 } 66 } 67 } 68 if ($state eq "incomplete") { 69 my $completion_score = 0; 70 foreach (reverse @chunk) { 71 $completion_score = (5 * $completion_score) + 72 $completion_score{$opener_for{$_}}; 73 } 74 push @completion_scores => $completion_score; 75 } 76 } 77 78 @completion_scores = sort { $a <=> $b } @completion_scores; 79 say "part 1 $error_score"; 80 say "part 2 ", $completion_scores[(scalar @completion_scores) / 2];