Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- $filename = "10.txt";
- open(FILE, $filename);
- @data = <FILE>;
- close(FILE);
- %scores = (')' => 3, ']' => 57, '}' => 1197, '>' => 25137); # Part1 score map
- %compscores = (')' => 1, ']' => 2, '}' => 3, '>' => 4); # Part2 score map
- $score = 0;
- %opposite = ('(' => ')', '[' => ']', '{' => '}', '<' => '>'); #Map of whats allowed as ending character to each begining character
- @incomplete = ();
- foreach $line (@data) {
- $line =~ s/[^\[\]\(\)\<\>\{\}]*//sgi;
- @chars = split("", $line);
- @stack = ();
- $found = 0;
- foreach $chr (@chars) {
- if ($chr =~ m/[\[\(\{\<]/) { #Found a beginning character - add to stack.
- unshift(@stack, $chr);
- }
- else
- {
- if ($opposite{$stack[0]} eq $chr) { #Ending character is valid - remove from stack.
- shift(@stack);
- }
- else
- { #Invalid ending character - add score to total, discard line ($found = 1) and end loop.
- $score = $score + $scores{$chr};
- $found = 1;
- last;
- }
- }
- }
- if ($found == 0) { #Didn't found anything - do autocomplete calculation instead
- $linescore = 0;
- foreach $rem (@stack) { #Whats left in stack is whats missing on the end.
- $linescore = $linescore * 5;
- $linescore = $linescore + $compscores{$opposite{$rem}}; #Use part2 and reverse map to calculate score.
- }
- push(@incomplete, $linescore);
- }
- }
- print $score."\n";
- @incomplete = sort { $a <=> $b } @incomplete; #Sort array.
- $element = ($#incomplete / 2); #Pick middle element of odd array
- print $incomplete[$element]."\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement