Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- $filename = "18.txt";
- open(FILE, $filename);
- @data = <FILE>;
- close(FILE);
- $sum = 0;
- $sumb = 0;
- foreach $line (@data) {
- $line =~ s/[^0-9\+\*\(\)]*//sgi; # Condition the input
- $sum = $sum + domath($line); #part1
- $sumb = $sumb + domathb($line); #part2
- }
- print "P1: ".$sum."\n";
- print "P2: ".$sumb."\n";
- sub domath() {
- my $inp = $_[0];
- my $s = "";
- my $p = "";
- my $matha = "";
- my $mathb = "";
- my $newinp;
- while ($inp =~ m/\(([^()]+)\)/) { #Run innermost parenthesis first
- $s = domath($1);
- $p = $1;
- $p =~ s/\(/\\\(/sgi;
- $p =~ s/\)/\\\)/sgi;
- $p =~ s/\+/\\\+/sgi;
- $p =~ s/\*/\\\*/sgi;
- $inp =~ s/\($p\)/$s/; #Replace inner parenthesis with result
- }
- while ($inp =~ m/([+*])/) { #No parenthesis left - run math parser until no operators are left.
- $char = $1;
- $matha = $inp;
- $matha =~ s/^(\d+)(.*)$/$1/; #Leftmost digit
- $mathb = $inp;
- $mathb =~ s/^(\d+)[+*](\d+)(.*)$/$2/; #Leftmost digit after operator
- if ($char eq "+") {
- $newinp = $matha + $mathb;
- }
- else
- {
- $newinp = $matha * $mathb;
- }
- $char =~ s/\+/\\\+/sgi;
- $char =~ s/\*/\\\*/sgi;
- $inp =~ s/$matha$char$mathb/$newinp/; #Replace expression with result.
- }
- return $inp;
- }
- sub domathb() {
- my $inp = $_[0];
- my $s = "";
- my $p = "";
- my $matha = "";
- my $mathb = "";
- my $newinp;
- while ($inp =~ m/\(([^()]+)\)/) { # same as before - run inner parenthesis first
- $s = domathb($1);
- $p = $1;
- $p =~ s/\(/\\\(/sgi;
- $p =~ s/\)/\\\)/sgi;
- $p =~ s/\+/\\\+/sgi;
- $p =~ s/\*/\\\*/sgi;
- $inp =~ s/\($p\)/$s/; #replace inner parenthesis with result
- }
- while ($inp =~ m/([+])/) { # Math parser for + only - run until theres no +'s left
- $matha = $inp;
- $matha =~ s/^(.*?)([0-9]+)\+([0-9]+)(.*?)$/$2/; # Digits before +
- $mathb = $inp;
- $mathb =~ s/^(.*?)([0-9]+)\+([0-9]+)(.*?)$/$3/; # Digits after +
- $newinp = $matha + $mathb;
- $inp =~ s/$matha\+$mathb/$newinp/; #Replace expression with result
- }
- while ($inp =~ m/([*])/) { # Math parser for * only - run until theres no *'s left
- $matha = $inp;
- $matha =~ s/^(.*?)([0-9]+)\*([0-9]+)(.*?)$/$2/; # Digits before *
- $mathb = $inp;
- $mathb =~ s/^(.*?)([0-9]+)\*([0-9]+)(.*?)$/$3/; # Digits after *
- $newinp = $matha * $mathb;
- $inp =~ s/$matha\*$mathb/$newinp/;
- }
- return $inp;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement