]> www.fi.muni.cz Git - aoc2021.git/blob - 36.pl
Day 25: pretty straightforward
[aoc2021.git] / 36.pl
1 #!/usr/bin/perl -w
2
3 use v5.16;
4
5 sub add {
6         $_ = "[$_[0],$_[1]]";
7         my $modified;
8         do {
9                 $modified = undef;
10                 my ($i, $depth) = (0, 0);
11                 while ($i < length) {
12                         $depth-- if substr($_, $i, 1) eq ']';
13                         $depth++ if substr($_, $i, 1) eq '[';
14                         
15                         if ($depth >= 5) {
16                                 pos = $i;
17                                 next unless s/\G\[(\d+),(\d+)\]/X/;
18                                 my ($l, $r) = ($1, $2);
19                                 s/(\d+)([^\d]*X)/($1+$l).$2/e;
20                                 s/(X[^\d]*)(\d+)/$1.($2+$r)/e;
21                                 s/X/0/;
22                                 $modified++; $depth--;
23                         }
24                         $i++;
25                 }
26                 $modified++ if s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e;
27         } while ($modified);
28         return $_;
29 }
30
31 sub magnitude { $_ = shift; 1 while s/\[(\d+),(\d+)\]/3*$1+2*$2/e; $_ }
32
33 use List::Util qw(reduce);
34
35 chomp (my @nums = <>);
36
37 say magnitude( reduce { add($a, $b) } @nums );
38
39 my $max = 0;
40 for my $i (0 .. $#nums) {
41 for my $j (0 .. $#nums) {
42         next if $i == $j;
43         my $r = magnitude( add($nums[$i], $nums[$j]) );
44         $max = $r if ($max < $r);
45 } }
46
47 say $max;