From 7135582c996b3dbc5fc402180c9cd58e5ccbbcce Mon Sep 17 00:00:00 2001 From: "Jan \"Yenya\" Kasprzak" Date: Wed, 8 Dec 2021 07:37:40 +0100 Subject: [PATCH] Day 8: a bit cleaner version --- 15.pl | 3 ++- 16.pl | 29 +++++++++++++++-------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/15.pl b/15.pl index 8a104b4..19d53b8 100755 --- a/15.pl +++ b/15.pl @@ -2,11 +2,12 @@ use v5.16; +my %l = map { $_ => 1 } qw(2 3 4 7); my $sum; while (<>) { chomp; s/.*\| //; - $sum += grep { my $x = length; $x == 2 || $x == 3 || $x == 4 || $x == 7; } split /\s+/; + $sum += grep { $l{length()} } split /\s+/; } say $sum; diff --git a/16.pl b/16.pl index fc9891e..86d8dfb 100755 --- 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; -- 2.43.5