]> www.fi.muni.cz Git - aoc2020.git/blob - 39.pl
Task 9 Perl Golf-style
[aoc2020.git] / 39.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 sub rows2str {
6         my (@rows) = @_;
7         return join("\n", @rows) . "\n";
8 }
9
10 sub rotate {
11         my ($str) = (@_);
12         my $dim =()= $str =~ /(\n)/g;
13         my $newstr = '';
14         for my $y (0 .. $dim-1) {
15                 for my $x (0 .. $dim-1) {
16                         $newstr .= substr($str, $y + ($dim+1)*($dim - $x - 1), 1);
17                 }
18                 $newstr .= "\n";
19         }
20         return $newstr;
21 }
22
23 sub flip {
24         my ($str) = @_;
25         return rows2str(map { join('', reverse split //) } split /\n/, $str);
26 }
27
28 sub rotate_or_flip {
29         my ($str, $count) = @_;
30         return $count == 4 ? flip($str) : rotate($str);
31 }
32
33 sub top_side {
34         $_[0] =~ /\A(.*?)\n/xms;
35         return $1;
36 }
37
38 my %top2tile;
39
40 local $/ = "\n\n";
41
42 while (<>) {
43         my ($id, $data) = /\ATile\s+(\d+):\n(.*?\n)\n?\z/xms;
44         for (1 .. 8) {
45                 push @{ $top2tile{top_side($data)} }, $id;
46                 $data = rotate_or_flip($data, $_);
47         }
48 }
49
50 my %single_ids;
51 for my $row (keys %top2tile) {
52         next if @{ $top2tile{$row} } != 1;
53         $single_ids{ $top2tile{$row}->[0] }++;
54 }
55
56 my @corners = grep { $single_ids{$_} == 4 } keys %single_ids;
57 print join('*', @corners), '=', eval join('*', @corners), "\n";