From 66c0e91aac46dc40c68bfc74db5bb21ff56857ef Mon Sep 17 00:00:00 2001 From: "Jan \"Yenya\" Kasprzak" Date: Sat, 18 Dec 2021 07:19:23 +0100 Subject: [PATCH] Day 18: regexes! and read the task carefully --- 35.pl | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 36.pl | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100755 35.pl create mode 100755 36.pl diff --git a/35.pl b/35.pl new file mode 100755 index 0000000..53e1e3e --- /dev/null +++ b/35.pl @@ -0,0 +1,46 @@ +#!/usr/bin/perl -w + +use v5.16; + +chomp (my $res = <>); +while (<>) { + chomp; + say "\nadd: $res\nto: $_"; + $res = "[$res,$_]"; + ACTION: + while (1) { + say "have: $res"; + # explode + my $depth = 0; + for my $i (0 .. length($res)-1) { + $depth++ if substr($res, $i, 1) eq '['; + $depth-- if substr($res, $i, 1) eq ']'; + + if ($depth >= 5) { + pos($res) = $i; + next if $res !~ /\G\[(\d+),(\d+)\]/; + say "explode at $i"; + pos($res) = $i; + $res =~ s/\G\[(\d+),(\d+)\]/X/; + say "X: $res"; + my $l = $1; + my $r = $2; + $res =~ s/(\d+)([^\d]*X)/($1+$l).$2/e; + $res =~ s/(X[^\d]*)(\d+)/"$1".($2+$r)/e; + $res =~ s/X/0/; + say "after: $res"; + next ACTION; + } + } + # split + if ($res =~ s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e) { + say "split: $res"; + next ACTION; + } + last; + } +} + +1 while $res =~ s/\[(\d+),(\d+)\]/3*$1+2*$2/e; +say $res; + diff --git a/36.pl b/36.pl new file mode 100755 index 0000000..4371f37 --- /dev/null +++ b/36.pl @@ -0,0 +1,58 @@ +#!/usr/bin/perl -w + +use v5.16; + +$/ = undef; +my @nums = split /\n/, <>; + +my $max = 0; +for my $i (0 .. $#nums) { +for my $j (0 .. $#nums) { + next if $i == $j; + my $r = add($nums[$i], $nums[$j]); + $max = $r if ($max < $r); +} } + +say $max; + +sub add { + my ($n1, $n2) = @_; + say "\nadd: $n1\nto: $n2"; + my $res = "[$n1,$n2]"; + ACTION: + while (1) { + say "have: $res"; + # explode + my $depth = 0; + for my $i (0 .. length($res)-1) { + $depth++ if substr($res, $i, 1) eq '['; + $depth-- if substr($res, $i, 1) eq ']'; + + if ($depth >= 5) { + pos($res) = $i; + next if $res !~ /\G\[(\d+),(\d+)\]/; + say "explode at $i"; + pos($res) = $i; + $res =~ s/\G\[(\d+),(\d+)\]/X/; + say "X: $res"; + my $l = $1; + my $r = $2; + $res =~ s/(\d+)([^\d]*X)/($1+$l).$2/e; + $res =~ s/(X[^\d]*)(\d+)/"$1".($2+$r)/e; + $res =~ s/X/0/; + say "after: $res"; + next ACTION; + } + } + # split + if ($res =~ s|\d{2,}|'['.int($&/2).','.int(($&+1)/2).']'|e) { + say "split: $res"; + next ACTION; + } + last; + } + 1 while $res =~ s/\[(\d+),(\d+)\]/3*$1+2*$2/e; + return $res; +} + + -- 2.43.0