]> www.fi.muni.cz Git - aoc.git/blobdiff - 2018/22.pl
Year 2018
[aoc.git] / 2018 / 22.pl
diff --git a/2018/22.pl b/2018/22.pl
new file mode 100755 (executable)
index 0000000..ba59374
--- /dev/null
@@ -0,0 +1,68 @@
+#!/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 %sq_cache;
+my ($maxx, $maxy, $maxsize, $maxpwr);
+sub square_at {
+       my ($x, $y, $sizex, $sizey) = @_;
+
+       return $sq_cache{$x,$y,$sizex,$sizey}
+               if defined $sq_cache{$x,$y,$sizex,$sizey};
+
+       my $sum;
+       if ($sizex == 1 && $sizey == 1) {
+               $sum = power_at($x, $y);
+       } elsif ($sizex == 1) {
+               $sum = square_at($x, $y, $sizex, $sizey-1)
+                       + power_at($x, $y+$sizey-1);
+       } elsif ($sizey == 1) {
+               $sum = square_at($x, $y, $sizex-1, $sizey)
+                       + power_at($x+$sizex-1, $y);
+       } else {
+               $sum = square_at($x, $y, $sizex-1, $sizey-1)
+                       + square_at($x+$sizex-1, $y, 1, $sizey-1)
+                       + square_at($x, $y+$sizey-1, $sizex-1, 1)
+                       + power_at($x+$sizex-1, $y+$sizey-1);
+       }
+       if ($sizex == $sizey && (!defined $maxpwr || $sum > $maxpwr)) {
+               $maxpwr = $sum;
+               $maxx = $x;
+               $maxy = $y;
+               $maxsize = $sizex;
+       }
+       $sq_cache{$x,$y,$sizex,$sizey} = $sum;
+}
+
+for my $size (1 .. 300) {
+       for my $x (1 .. 301-$size) {
+               for my $y (1 .. 301-$size) {
+                       my $sz = square_at($x, $y, $size, $size);
+                       # say "$x,$y,$size = $sz";
+               }
+       }
+       say "size $size, $maxx,$maxy,$maxsize = $maxpwr";
+}
+
+say "$maxx,$maxy,$maxsize = $maxpwr";
+                       
+               
+       
+       
+