From: Jan "Yenya" Kasprzak <kas@fi.muni.cz>
Date: Sat, 18 Dec 2021 06:19:23 +0000 (+0100)
Subject: Day 18: regexes! and read the task carefully
X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?a=commitdiff_plain;h=66c0e91aac46dc40c68bfc74db5bb21ff56857ef;p=aoc2021.git

Day 18: regexes! and read the task carefully
---

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;
+}
+
+