Skip to content

Instantly share code, notes, and snippets.

@kivikakk
Created December 9, 2015 05:21
Show Gist options
  • Select an option

  • Save kivikakk/66ac992872ab9d5c0656 to your computer and use it in GitHub Desktop.

Select an option

Save kivikakk/66ac992872ab9d5c0656 to your computer and use it in GitHub Desktop.
use 5.018;
my %nodes = ();
open(my $fh, '<', 'input') or die "can't read input: $!";
while (my $line = <$fh>) {
if ($line =~ /^(\w+) to (\w+) = (\d+)$/) {
$nodes{$1}{$2} = $3;
$nodes{$2}{$1} = $3;
}
}
close($fh);
my @distances = ();
sub chart_from {
my ($start, $dist, $remaining) = @_;
my @remaining = @$remaining;
if (@remaining == 0) {
say "done: $dist";
}
foreach my $next (@remaining) {
my @thisremaining = grep { $_ ne $next } @remaining;
chart_from($next, $dist + $nodes{$start}{$next}, \@thisremaining);
}
}
foreach my $start (keys %nodes) {
my @remaining = grep { $_ ne $start } keys %nodes;
chart_from($start, 0, \@remaining);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment