]> www.fi.muni.cz Git - aoc.git/blob - 2018/22.pl
Day 25: examining the input
[aoc.git] / 2018 / 22.pl
1 #!/usr/bin/perl -w
2
3 use v5.30;
4 use strict;
5
6 my $serial = shift @ARGV;
7
8 my %cache;
9 sub power_at {
10         my ($x, $y) = @_;
11         return $cache{$x,$y} if defined $cache{$x,$y};
12
13         my $rack_id = $x + 10;
14         my $power = ($rack_id * $y + $serial) * $rack_id;
15         $power = "000" . $power;
16         $power =~ s/.*(.)..\z/$1/;
17         $power -= 5;
18         return $cache{$x,$y} = $power;
19 }
20
21 my %sq_cache;
22 my ($maxx, $maxy, $maxsize, $maxpwr);
23 sub square_at {
24         my ($x, $y, $sizex, $sizey) = @_;
25
26         return $sq_cache{$x,$y,$sizex,$sizey}
27                 if defined $sq_cache{$x,$y,$sizex,$sizey};
28
29         my $sum;
30         if ($sizex == 1 && $sizey == 1) {
31                 $sum = power_at($x, $y);
32         } elsif ($sizex == 1) {
33                 $sum = square_at($x, $y, $sizex, $sizey-1)
34                         + power_at($x, $y+$sizey-1);
35         } elsif ($sizey == 1) {
36                 $sum = square_at($x, $y, $sizex-1, $sizey)
37                         + power_at($x+$sizex-1, $y);
38         } else {
39                 $sum = square_at($x, $y, $sizex-1, $sizey-1)
40                         + square_at($x+$sizex-1, $y, 1, $sizey-1)
41                         + square_at($x, $y+$sizey-1, $sizex-1, 1)
42                         + power_at($x+$sizex-1, $y+$sizey-1);
43         }
44         if ($sizex == $sizey && (!defined $maxpwr || $sum > $maxpwr)) {
45                 $maxpwr = $sum;
46                 $maxx = $x;
47                 $maxy = $y;
48                 $maxsize = $sizex;
49         }
50         $sq_cache{$x,$y,$sizex,$sizey} = $sum;
51 }
52
53 for my $size (1 .. 300) {
54         for my $x (1 .. 301-$size) {
55                 for my $y (1 .. 301-$size) {
56                         my $sz = square_at($x, $y, $size, $size);
57                         # say "$x,$y,$size = $sz";
58                 }
59         }
60         say "size $size, $maxx,$maxy,$maxsize = $maxpwr";
61 }
62
63 say "$maxx,$maxy,$maxsize = $maxpwr";
64                         
65                 
66         
67         
68