#!/usr/bin/perl -w

use v5.38;
use experimental 'multidimensional', 'for_list', 'builtin';
use builtin 'indexed';
use List::Util;
use Y::AoC::Task;
$; = ';';
# t;

my @map = map { chomp; [ split // ] } <>;
my $xmax = @{ $map[0] };
my $ymax = @map;

my $sum;
my %seen;
my %gear;

sub test_sym {
	my ($prev, $x, $y, @d) = @_;
	for my ($dx, $dy) (@d) {
		my ($nx, $ny) = ($x+$dx, $y+$dy);
		next if $nx < 0 || $nx >= $xmax || $ny < 0 || $ny >= $ymax;
		if ($map[$ny][$nx] eq '*') {
			$$prev = [$nx, $ny];
		}
	}
}

for my $y (0 .. $ymax-1) {
for my $x (0 .. $xmax-1) {
	my $n = $map[$y][$x];
	next if $n !~ /\d/ || $seen{$x,$y}++;
	my $dx = 1;
	while ($x+$dx < $xmax && $map[$y][$x+$dx] =~ /\d/) {
		$n*=10; $n+= $map[$y][$x+$dx];
		$seen{$x+$dx,$y} = 1;
		$dx++;
		say "$n at $x..", $x+$dx, ", $y";
	}
	my $sym;
	for my $x1 (-1 .. $dx) {
		test_sym(\$sym, $x, $y, $x1, -1, $x1, 0, $x1, +1);
	}
	if (defined $sym) {
		my ($sx, $sy) = @$sym;
		push @{ $gear{$sx,$sy} }, $n;
		say "Star at $sx, $sy";
	}
} }


for my $k (keys %gear) {
	my @coords = @{ $gear{$k} };
	next if @coords != 2;
	$sum += $coords[0] * $coords[1];
}

say $sum;
