]> www.fi.muni.cz Git - aoc.git/blobdiff - 2020/39.pl
Moved 2020 to a subdir
[aoc.git] / 2020 / 39.pl
diff --git a/2020/39.pl b/2020/39.pl
new file mode 100755 (executable)
index 0000000..40f98ab
--- /dev/null
@@ -0,0 +1,57 @@
+#!/usr/bin/perl -w
+
+use strict;
+
+sub rows2str {
+       my (@rows) = @_;
+       return join("\n", @rows) . "\n";
+}
+
+sub rotate {
+       my ($str) = (@_);
+       my $dim =()= $str =~ /(\n)/g;
+       my $newstr = '';
+       for my $y (0 .. $dim-1) {
+               for my $x (0 .. $dim-1) {
+                       $newstr .= substr($str, $y + ($dim+1)*($dim - $x - 1), 1);
+               }
+               $newstr .= "\n";
+       }
+       return $newstr;
+}
+
+sub flip {
+       my ($str) = @_;
+       return rows2str(map { join('', reverse split //) } split /\n/, $str);
+}
+
+sub rotate_or_flip {
+       my ($str, $count) = @_;
+       return $count == 4 ? flip($str) : rotate($str);
+}
+
+sub top_side {
+       $_[0] =~ /\A(.*?)\n/xms;
+       return $1;
+}
+
+my %top2tile;
+
+local $/ = "\n\n";
+
+while (<>) {
+       my ($id, $data) = /\ATile\s+(\d+):\n(.*?\n)\n?\z/xms;
+       for (1 .. 8) {
+               push @{ $top2tile{top_side($data)} }, $id;
+               $data = rotate_or_flip($data, $_);
+       }
+}
+
+my %single_ids;
+for my $row (keys %top2tile) {
+       next if @{ $top2tile{$row} } != 1;
+       $single_ids{ $top2tile{$row}->[0] }++;
+}
+
+my @corners = grep { $single_ids{$_} == 4 } keys %single_ids;
+print join('*', @corners), '=', eval join('*', @corners), "\n";