]> www.fi.muni.cz Git - aoc2021.git/blobdiff - 16.pl
Day 8: a bit cleaner version
[aoc2021.git] / 16.pl
diff --git a/16.pl b/16.pl
index fc9891e5b1d532d11ae668bc455a0ffb327d7580..86d8dfbbaa81c6361bd38892187fa3261ea938cb 100755 (executable)
--- a/16.pl
+++ b/16.pl
@@ -30,31 +30,32 @@ sub do_perms {
        }
 }
 
-do_perms ('', qw(a b c d e f g));
+do_perms('', qw(a b c d e f g));
+
+sub permute {
+       my ($val, $perm) = @_;
+       eval "\$val =~ y/abcdefg/$perm/";
+       join('', sort split //, $val);
+}
 
 my $sum = 0;
 ROW:
 while (<>) {
        chomp;
        my ($inv, $outv) = split /\s+\|\s+/;
-       my (@in) = split /\s+/, $inv;
+       my (@in) = sort { length $a <=> length $b } split /\s+/, $inv;
+       # say "$inv => ", join(' ', @in);
        my (@out) = split /\s+/, $outv;
 
-       PERM:
-       for my $perm (@perms) {
+       PERM: for my $perm (@perms) {
                for my $i (@in) {
-                       my $ni = $i;
-                       eval "\$ni =~ y/abcdefg/$perm/";
-                       my $sorted = join('', sort split //, $ni);
-                       # say "i=$i ni=$ni sorted=$sorted";
-                       next PERM if !defined $digits{$sorted};
+                       my $ni = permute($i, $perm);
+                       next PERM if !defined $digits{$ni};
                }
-               my $rv = '';
+               my $rv;
                for my $o (@out) {
-                       my $no = $o;
-                       eval "\$no =~ y/abcdefg/$perm/";
-                       my $nsorted = join('', sort split //, $no);
-                       $rv .= $digits{$nsorted};
+                       my $no = permute($o, $perm);
+                       $rv .= $digits{$no};
                }
                $sum += $rv;
                next ROW;