]> www.fi.muni.cz Git - aoc2021.git/blob - 35.pl
Day 25: pretty straightforward
[aoc2021.git] / 35.pl
1 #!/usr/bin/perl -w
2
3 use v5.16;
4
5 chomp (my $res = <>);
6 while (<>) {
7         chomp;
8         say "\nadd:   $res\nto:    $_";
9         $res = "[$res,$_]";
10         ACTION:
11         while (1) {
12                 say "have:  $res";
13                 # explode
14                 my $depth = 0;
15                 for my $i (0 .. length($res)-1) {
16                         $depth++ if substr($res, $i, 1) eq '[';
17                         $depth-- if substr($res, $i, 1) eq ']';
18                         
19                         if ($depth >= 5) {
20                                 pos($res) = $i;
21                                 next if $res !~ /\G\[(\d+),(\d+)\]/;
22                                 say "explode at $i";
23                                 pos($res) = $i;
24                                 $res =~ s/\G\[(\d+),(\d+)\]/X/;
25                                 say "X:     $res";
26                                 my $l = $1;
27                                 my $r = $2;
28                                 $res =~ s/(\d+)([^\d]*X)/($1+$l).$2/e;
29                                 $res =~ s/(X[^\d]*)(\d+)/"$1".($2+$r)/e;
30                                 $res =~ s/X/0/;
31                                 say "after: $res";
32                                 next ACTION;
33                         }
34                 }
35                 # split
36                 if ($res =~ s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e) {
37                         say "split: $res";
38                         next ACTION;
39                 }
40                 last;
41         }
42 }
43
44 1 while $res =~ s/\[(\d+),(\d+)\]/3*$1+2*$2/e;
45 say $res;
46