]> www.fi.muni.cz Git - aoc.git/blob - 2022/18.pl
Day 9: quite tedious, resembling real work :-)
[aoc.git] / 2022 / 18.pl
1 #!/usr/bin/perl -w
2
3 use v5.36;
4 use strict;
5 use experimental 'multidimensional';
6
7 my %seen = ("0,0" => 1);
8 my @knots;
9 push @knots, [0, 0] for 1 .. 10;
10
11 sub follow ($x, $y, $tx, $ty) {
12         if ($x == $tx) {
13                 if ($y == $ty - 2) {
14                         $ty--;
15                 } elsif ($y == $ty + 2) {
16                         $ty++;
17                 }
18         } elsif ($y == $ty) {
19                 if ($x == $tx - 2) {
20                         $tx--;
21                 } elsif ($x == $tx + 2) {
22                         $tx++;
23                 }
24         } elsif ($x == $tx - 2) {
25                 $tx--;
26                 if ($y > $ty) {
27                         $ty++;
28                 } else {
29                         $ty--
30                 }
31         } elsif ($x == $tx + 2) {
32                 $tx++;
33                 if ($y > $ty) {
34                         $ty++;
35                 } else {
36                         $ty--;
37                 }
38         } elsif ($y == $ty - 2) {
39                 $ty--;
40                 if ($x > $tx) {
41                         $tx++;
42                 } else {
43                         $tx--;
44                 }
45         } elsif ($y == $ty + 2) {
46                 $ty++;
47                 if ($x > $tx) {
48                         $tx++;
49                 } else {
50                         $tx--;
51                 }
52         }
53         ($tx, $ty);
54 }
55
56 while (<>) {
57         my ($dir, $len) = /^(.) (\d+)/;
58
59         while ($len--) {
60                 if ($dir eq 'U') {
61                         $knots[0][1]--;
62                 } elsif ($dir eq 'D') {
63                         $knots[0][1]++;
64                 } elsif ($dir eq 'L') {
65                         $knots[0][0]--;
66                 } elsif ($dir eq 'R') {
67                         $knots[0][0]++;
68                 }
69                 
70                 for (1 .. $#knots) {
71                         ($knots[$_][0], $knots[$_][1]) = follow(
72                                 @{ $knots[$_-1] },
73                                 @{ $knots[$_] }
74                         );
75                 }
76         
77                 $seen{"$knots[-1][0],$knots[-1][1]"}++;
78         }
79 }
80
81 say scalar keys %seen;
82