]> www.fi.muni.cz Git - aoc2021.git/blob - 36.pl
Day 18: regexes! and read the task carefully
[aoc2021.git] / 36.pl
1 #!/usr/bin/perl -w
2
3 use v5.16;
4
5 $/ = undef;
6 my @nums = split /\n/, <>;
7
8 my $max = 0;
9 for my $i (0 .. $#nums) {
10 for my $j (0 .. $#nums) {
11         next if $i == $j;
12         my $r = add($nums[$i], $nums[$j]);
13         $max = $r if ($max < $r);
14 } }
15
16 say $max;
17
18 sub add {
19         my ($n1, $n2) = @_;
20         say "\nadd:   $n1\nto:    $n2";
21         my $res = "[$n1,$n2]";
22         ACTION:
23         while (1) {
24                 say "have:  $res";
25                 # explode
26                 my $depth = 0;
27                 for my $i (0 .. length($res)-1) {
28                         $depth++ if substr($res, $i, 1) eq '[';
29                         $depth-- if substr($res, $i, 1) eq ']';
30                         
31                         if ($depth >= 5) {
32                                 pos($res) = $i;
33                                 next if $res !~ /\G\[(\d+),(\d+)\]/;
34                                 say "explode at $i";
35                                 pos($res) = $i;
36                                 $res =~ s/\G\[(\d+),(\d+)\]/X/;
37                                 say "X:     $res";
38                                 my $l = $1;
39                                 my $r = $2;
40                                 $res =~ s/(\d+)([^\d]*X)/($1+$l).$2/e;
41                                 $res =~ s/(X[^\d]*)(\d+)/"$1".($2+$r)/e;
42                                 $res =~ s/X/0/;
43                                 say "after: $res";
44                                 next ACTION;
45                         }
46                 }
47                 # split
48                 if ($res =~ s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e) {
49                         say "split: $res";
50                         next ACTION;
51                 }
52                 last;
53         }
54         1 while $res =~ s/\[(\d+),(\d+)\]/3*$1+2*$2/e;
55         return $res;
56 }
57
58