#!/usr/bin/perl -w

use v5.30;
use strict;

my $serial = shift @ARGV;

my %cache;
sub power_at {
	my ($x, $y) = @_;
	return $cache{$x,$y} if defined $cache{$x,$y};

	my $rack_id = $x + 10;
	my $power = ($rack_id * $y + $serial) * $rack_id;
	$power = "000" . $power;
	$power =~ s/.*(.)..\z/$1/;
	$power -= 5;
	return $cache{$x,$y} = $power;
}

my ($maxx, $maxy, $maxpwr);
for my $x (1 .. 300) {
	for my $y (1 .. 300) {
		my $sum;
		for my $dx (0 .. 2) {
			next if $x + $dx > 300;
			for my $dy (0 .. 2) {
				next if $y + $dy > 300;
				$sum += power_at($x+$dx, $y+$dy);
			}
		}
		if (!defined $maxpwr || $sum > $maxpwr) {
			$maxpwr = $sum;
			$maxx = $x;
			$maxy = $y;
		}
	}
}

say power_at(33,45);
say "$maxx,$maxy = $maxpwr";
			
		
	
	

