musifter

AoC 2015, day 9 (Perl)

Jan 8th, 2026 (edited)
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.82 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature             qw(say);
  7. use List::AllUtils      qw(minmax);
  8.  
  9. # Build distance table
  10. my %table;
  11.  
  12. while (<>) {
  13.     m#(\w+) to (\w+) = (\d+)#;
  14.     $table{$1}{$2} = $table{$2}{$1} = $3;
  15. }
  16.  
  17. # Add extra node at zero distance from all to handle arbitrary start location
  18. $table{'NorthPole'}->%* = map {$_ => 0} keys %table;
  19.  
  20. # Recurse to generate path permutations
  21. sub recurse_path {
  22.     my ($dist, $loc, @list) = @_;
  23.     my @res;
  24.  
  25.     return ($dist)  if (!@list);
  26.  
  27.     foreach my $next (@list) {
  28.         push( @res, &recurse_path($dist + $table{$loc}{$next}, $next, grep {$next ne $_} @list) );
  29.     }
  30.  
  31.     return (minmax @res);
  32. }
  33.  
  34. my @res = &recurse_path( 0, 'NorthPole', keys $table{'NorthPole'}->%* );
  35.  
  36. say "Part 1: ", $res[0];
  37. say "Part 2: ", $res[1];
  38.  
Advertisement
Add Comment
Please, Sign In to add comment