Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use List::AllUtils qw(minmax);
- # Build distance table
- my %table;
- while (<>) {
- m#(\w+) to (\w+) = (\d+)#;
- $table{$1}{$2} = $table{$2}{$1} = $3;
- }
- # Add extra node at zero distance from all to handle arbitrary start location
- $table{'NorthPole'}->%* = map {$_ => 0} keys %table;
- # Recurse to generate path permutations
- sub recurse_path {
- my ($dist, $loc, @list) = @_;
- my @res;
- return ($dist) if (!@list);
- foreach my $next (@list) {
- push( @res, &recurse_path($dist + $table{$loc}{$next}, $next, grep {$next ne $_} @list) );
- }
- return (minmax @res);
- }
- my @res = &recurse_path( 0, 'NorthPole', keys $table{'NorthPole'}->%* );
- say "Part 1: ", $res[0];
- say "Part 2: ", $res[1];
Advertisement
Add Comment
Please, Sign In to add comment