#!/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;

