Advertisement
Guest User

Untitled

a guest
Dec 9th, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.97 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. $filename = "10.txt";
  4.  
  5. open(FILE, $filename);
  6. @data = <FILE>;
  7. close(FILE);
  8.  
  9. %scores = (')' => 3, ']' => 57, '}' => 1197, '>' => 25137); # Part1 score map
  10. %compscores = (')' => 1, ']' => 2, '}' => 3, '>' => 4); # Part2 score map
  11. $score = 0;
  12. %opposite = ('(' => ')', '[' => ']', '{' => '}', '<' => '>'); #Map of whats allowed as ending character to each begining character
  13. @incomplete = ();
  14.  
  15. foreach $line (@data) {
  16.         $line =~ s/[^\[\]\(\)\<\>\{\}]*//sgi;
  17.         @chars = split("", $line);
  18.         @stack = ();
  19.         $found = 0;
  20.         foreach $chr (@chars) {
  21.                 if ($chr =~ m/[\[\(\{\<]/) { #Found a beginning character - add to stack.
  22.                         unshift(@stack, $chr);
  23.                 }
  24.                 else
  25.                 {
  26.                         if ($opposite{$stack[0]} eq $chr) { #Ending character is valid - remove from stack.
  27.                                 shift(@stack);
  28.                         }
  29.                         else
  30.                         {   #Invalid ending character - add score to total, discard line ($found = 1) and end loop.
  31.                                 $score = $score + $scores{$chr};
  32.                                 $found = 1;
  33.                                 last;
  34.                         }
  35.                 }
  36.  
  37.  
  38.         }
  39.  
  40.         if ($found == 0) { #Didn't found anything - do autocomplete calculation instead
  41.                 $linescore = 0;
  42.                 foreach $rem (@stack) { #Whats left in stack is whats missing on the end.
  43.                         $linescore = $linescore * 5;
  44.                         $linescore = $linescore + $compscores{$opposite{$rem}}; #Use part2 and reverse map to calculate score.
  45.                 }
  46.                 push(@incomplete, $linescore);
  47.         }
  48.  
  49. }
  50.  
  51.  
  52. print $score."\n";
  53.  
  54. @incomplete = sort { $a <=> $b } @incomplete; #Sort array.
  55.  
  56. $element = ($#incomplete / 2); #Pick middle element of odd array
  57.  
  58. print $incomplete[$element]."\n";
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement