2016-12-05 Advent of Code in Perl 5

Today I don’t have a lot of time for Advent of Code. So, Perl 5 it is. My Swiss Army knife!

Advent of Code

I’ll have to save the interesting languages for days when I have a lot of time. This will be hard. 🙁

Question 1: You start with a string such as “abc” and append an index, then compute the MD5 hash, and if its hex representation starts with five zeroes, then the sixth character is a letter in your password. Keep increasing the index until you have eight letters for your password. Using “abc” as the example, the first match would be “abc3231929” which produces a hash of “00000155f8105dff7f56ee10fa9b9abd” and thus the first letter of the password would be “1”.

use Modern::Perl;
use Digest::MD5 qw(md5_hex);

my $prefix = 'abc';
my $i = 0;
my $length = 0;
my $pwd;
while ($length < 8) {
  my $digest = md5_hex($prefix . $i++);
  if ('00000' eq substr($digest, 0, 5)) {
    $pwd .= substr($digest, 5, 1);
    $length++;
    print "$pwd\n";
  }
}

Question 2: Same as before, but now the the sixth character indicates the *position* of the seventh character. In the example above, this means that position 1 has the number “5”. The password is zero indexed. Ignore positions outside the password and don’t overwrite characters you’ve alreay found.

use Modern::Perl;
use Digest::MD5 qw(md5_hex);

$" = '';
my $prefix = 'abc';
my $i = 0;
my $length = 0;
my @pwd = qw(_ _ _ _ _ _ _ _);
while ($length < 8) {
  my $digest = md5_hex($prefix . $i++);
  if ('00000' eq substr($digest, 0, 5)) {
    my $p = hex(substr($digest, 5, 1));
    next if $p >= 8 or $pwd[$p] ne "_";
    my $c = substr($digest, 6, 1);
    $length++;
    $pwd[$p] = $c;
    print "@pwd\n";
  }
}

​#Perl ​#Advent of Code ​#Programming