Advertisement
mscha

AoC 2016 day 14 (with Inline::Perl5)

Dec 15th, 2016
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 2.01 KB | None | 0 0
  1. #!/usr/bin/env perl6
  2.  
  3. use v6.c;
  4.  
  5. #use Digest::MD5;   # Too slow, use Perl 5 version through Inline::Perl5
  6. use Digest::MD5:from<Perl5> 'md5_hex';
  7.  
  8. sub md5_repeated(Str $str is copy, Int $iterations)
  9. {
  10.     # Way too slow - probably overhead of using Inline::Perl5 2017 times
  11.     #$str = md5_hex($str) for ^$iterations;
  12.     #return $str;
  13.  
  14.     # Do the whole thing in Perl 5 code instead
  15.     use MONKEY-SEE-NO-EVAL;
  16.     return EVAL "my \$s = '$str'; for (1..$iterations) \{ \$s = md5_hex(\$s); \}; \$s;", :lang<Perl5>;
  17. }
  18.  
  19. my regex triple { (\w) ** 3 <?{ [eq] @($/[0]) }> }
  20. sub triples(Str $s)
  21. {
  22.     # Only the first one!
  23.     #return $s.comb(&triple).unique».substr(0, 1);
  24.     return $s.comb(&triple, 1)».substr(0, 1);
  25. }
  26.  
  27. my regex quintuple { (\w) ** 5 <?{ [eq] @($/[0]) }> }
  28. sub quintuples(Str $s)
  29. {
  30.     return $s.comb(&quintuple).unique».substr(0, 1);
  31. }
  32.  
  33. sub key-info(Str $salted-index)
  34. {
  35.     #my $hash = md5_hex($salted-index);                  # part 1
  36.     my $hash = md5_repeated($salted-index, 2017);       # part 2
  37.     return { hash=>$hash, triples=>triples($hash), quintuples=>quintuples($hash) };
  38. }
  39.  
  40. sub test-key(Str $salt, Int $index)
  41. {
  42.     state %key-info;
  43.  
  44.     %key-info{$salt~$index} //= key-info($salt~$index);
  45.     my @triples = %key-info{$salt~$index}<triples>.flat;    # Not sure why flat is needed
  46.     return Nil unless @triples;
  47.  
  48.     for $index+1 .. $index+1000 -> $i {
  49.         %key-info{$salt~$i} //= key-info($salt~$i);
  50.         my @quintuples = %key-info{$salt~$i}<quintuples>.flat;
  51.         return %key-info{$salt~$index}<hash> if @quintuples && any(@triples) eq any(@quintuples);
  52.     }
  53.  
  54.     return Nil;
  55. }
  56.  
  57. multi sub MAIN(IO() $inputfile where *.f)
  58. {
  59.     my ($salt) = $inputfile.words;
  60.     MAIN($salt);
  61. }
  62.  
  63. multi sub MAIN(Str $salt where !*.IO.f)
  64. {
  65.     my @keys;
  66.  
  67.     for 1..-> $i {
  68.         if my $hash = test-key($salt, $i) {
  69.             @keys.push($hash);
  70.             say "[#@keys.elems()] $i: $hash";
  71.             last if @keys.elems == 64;
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement