]> www.fi.muni.cz Git - aoc.git/blobdiff - 2016/42.pl
The rest of Year 2016
[aoc.git] / 2016 / 42.pl
diff --git a/2016/42.pl b/2016/42.pl
new file mode 100755 (executable)
index 0000000..ab06a7d
--- /dev/null
@@ -0,0 +1,60 @@
+#!/usr/bin/perl -w
+
+use strict;
+use v5.30;
+
+my $data = 'abcdefgh';
+# my $data = 'abcde';
+chomp (my @rules = <>);
+
+sub scramble {
+       my $data = shift;
+       for (@rules) {
+               if (/swap position (\d+) with position (\d+)/) {
+                       (substr($data, $1, 1), substr($data, $2, 1))
+                               = (substr($data, $2, 1), substr($data, $1, 1));
+               } elsif (/swap letter (\w) with letter (\w)/) {
+                       eval "\$data =~ y/$1$2/$2$1/";
+               } elsif (/rotate left (\d+) /) {
+                       my $n = $1;
+                       $data =~ s/^(.{$n})(.*)/$2$1/;
+               } elsif (/rotate right (\d+) /) {
+                       my $n = $1;
+                       $data =~ s/^(.*)(.{$n})/$2$1/;
+               } elsif (/rotate based on position of letter (\w)/) {
+                       my $l = $1;
+                       my ($pref) = $data =~ /^(.*$l)/;
+                       my $pos = length($pref);
+                       $pos++ if $pos > 4;
+                       $pos -= length($data) if $pos >= length($data);
+                       $data =~ s/^(.*)(.{$pos})/$2$1/ if $pos;
+               } elsif (/reverse positions (\d+) through (\d+)/) {
+                       substr($data, $1, $2-$1+1) = join('', reverse split //,
+                               substr($data, $1, $2-$1+1));
+               } elsif (/move position (\d+) to position (\d+)/) {
+                       my $l = substr($data, $1, 1);
+                       substr($data, $1, 1) = '';
+                       substr($data, $2, 0) = $l;
+               } else {
+                       die "Unknown command $_.";
+               }
+       }
+       return $data;
+}
+
+sub perm {
+       my ($pass, @rest) = @_;
+       if (!@rest) {
+               if (scramble($pass) eq 'fbgdceah') {
+                       say "found $pass";
+                       exit 0;
+               }
+       }
+       for my $i (0 .. $#rest) {
+               my @nr = @rest;
+               my $c = splice (@nr, $i, 1);
+               perm("$pass$c", @nr);
+       }
+}
+
+perm('', split //, 'abcdefgh');