]> www.fi.muni.cz Git - aoc.git/blobdiff - 2021/36.pl
Moved 2021 to a subdir
[aoc.git] / 2021 / 36.pl
diff --git a/2021/36.pl b/2021/36.pl
new file mode 100755 (executable)
index 0000000..3047f40
--- /dev/null
@@ -0,0 +1,47 @@
+#!/usr/bin/perl -w
+
+use v5.16;
+
+sub add {
+       $_ = "[$_[0],$_[1]]";
+       my $modified;
+       do {
+               $modified = undef;
+               my ($i, $depth) = (0, 0);
+               while ($i < length) {
+                       $depth-- if substr($_, $i, 1) eq ']';
+                       $depth++ if substr($_, $i, 1) eq '[';
+                       
+                       if ($depth >= 5) {
+                               pos = $i;
+                               next unless s/\G\[(\d+),(\d+)\]/X/;
+                               my ($l, $r) = ($1, $2);
+                               s/(\d+)([^\d]*X)/($1+$l).$2/e;
+                               s/(X[^\d]*)(\d+)/$1.($2+$r)/e;
+                               s/X/0/;
+                               $modified++; $depth--;
+                       }
+                       $i++;
+               }
+               $modified++ if s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e;
+       } while ($modified);
+       return $_;
+}
+
+sub magnitude { $_ = shift; 1 while s/\[(\d+),(\d+)\]/3*$1+2*$2/e; $_ }
+
+use List::Util qw(reduce);
+
+chomp (my @nums = <>);
+
+say magnitude( reduce { add($a, $b) } @nums );
+
+my $max = 0;
+for my $i (0 .. $#nums) {
+for my $j (0 .. $#nums) {
+       next if $i == $j;
+       my $r = magnitude( add($nums[$i], $nums[$j]) );
+       $max = $r if ($max < $r);
+} }
+
+say $max;