]> www.fi.muni.cz Git - aoc.git/blob - 2016/42.pl
The rest of Year 2016
[aoc.git] / 2016 / 42.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4 use v5.30;
5
6 my $data = 'abcdefgh';
7 # my $data = 'abcde';
8 chomp (my @rules = <>);
9
10 sub scramble {
11         my $data = shift;
12         for (@rules) {
13                 if (/swap position (\d+) with position (\d+)/) {
14                         (substr($data, $1, 1), substr($data, $2, 1))
15                                 = (substr($data, $2, 1), substr($data, $1, 1));
16                 } elsif (/swap letter (\w) with letter (\w)/) {
17                         eval "\$data =~ y/$1$2/$2$1/";
18                 } elsif (/rotate left (\d+) /) {
19                         my $n = $1;
20                         $data =~ s/^(.{$n})(.*)/$2$1/;
21                 } elsif (/rotate right (\d+) /) {
22                         my $n = $1;
23                         $data =~ s/^(.*)(.{$n})/$2$1/;
24                 } elsif (/rotate based on position of letter (\w)/) {
25                         my $l = $1;
26                         my ($pref) = $data =~ /^(.*$l)/;
27                         my $pos = length($pref);
28                         $pos++ if $pos > 4;
29                         $pos -= length($data) if $pos >= length($data);
30                         $data =~ s/^(.*)(.{$pos})/$2$1/ if $pos;
31                 } elsif (/reverse positions (\d+) through (\d+)/) {
32                         substr($data, $1, $2-$1+1) = join('', reverse split //,
33                                 substr($data, $1, $2-$1+1));
34                 } elsif (/move position (\d+) to position (\d+)/) {
35                         my $l = substr($data, $1, 1);
36                         substr($data, $1, 1) = '';
37                         substr($data, $2, 0) = $l;
38                 } else {
39                         die "Unknown command $_.";
40                 }
41         }
42         return $data;
43 }
44
45 sub perm {
46         my ($pass, @rest) = @_;
47         if (!@rest) {
48                 if (scramble($pass) eq 'fbgdceah') {
49                         say "found $pass";
50                         exit 0;
51                 }
52         }
53         for my $i (0 .. $#rest) {
54                 my @nr = @rest;
55                 my $c = splice (@nr, $i, 1);
56                 perm("$pass$c", @nr);
57         }
58 }
59
60 perm('', split //, 'abcdefgh');