079 Passcode derivation.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 24 March 2022
  4. # https://github.com/trizen
  5. # Passcode derivation
  6. # https://projecteuler.net/problem=79
  7. # General recursive solution.
  8. # Runtime: 0.158s
  9. use 5.020;
  10. use warnings;
  11. use List::Util qw(min);
  12. use experimental qw(signatures);
  13. sub find_candidates ($callback, $a, $b, $re_a = join('.*?', @$a), $re_b = join('.*?', @$b), $a_i = 0, $b_i = 0, $solution = [])
  14. {
  15. if (join('', @$solution) =~ $re_a and join('', @$solution) =~ $re_b) {
  16. $callback->($solution);
  17. return $solution;
  18. }
  19. if (($a_i <= $#$a) && ($b_i <= $#$b) && ($a->[$a_i] == $b->[$b_i])) {
  20. __SUB__->($callback, $a, $b, $re_a, $re_b, $a_i + 1, $b_i + 1, [@$solution, $a->[$a_i]]);
  21. }
  22. __SUB__->($callback, $a, $b, $re_a, $re_b, $a_i + 1, $b_i, [@$solution, $a->[$a_i]]) if ($a_i <= $#$a);
  23. __SUB__->($callback, $a, $b, $re_a, $re_b, $a_i, $b_i + 1, [@$solution, $b->[$b_i]]) if ($b_i <= $#$b);
  24. }
  25. my @passcodes = sort { $a <=> $b } qw(
  26. 319 680 180 690 129 620 762 689 318 368 710 720 629 168 160 716
  27. 731 736 729 316 769 290 719 389 162 289 718 790 890 362 760 380 728
  28. );
  29. my @candidates = [split(//, shift(@passcodes))];
  30. while (@passcodes) {
  31. my $b = [split(//, shift(@passcodes))];
  32. my @new_candidates;
  33. foreach my $a (@candidates) {
  34. find_candidates(
  35. sub ($solution) {
  36. push @new_candidates, $solution;
  37. },
  38. $a, $b
  39. );
  40. }
  41. @new_candidates = do { # remove duplicates
  42. my %seen;
  43. grep { !$seen{join('', @$_)}++ } @new_candidates;
  44. };
  45. my $min_len = min(map { $#$_ } @new_candidates);
  46. @candidates = grep { $#$_ == $min_len } @new_candidates;
  47. say sprintf("Found: %s candidates (best: %s)", scalar(@candidates), join('', @{$candidates[0]}));
  48. }
  49. say "Final candidates: ", join(', ', map { join('', @$_) } @candidates);