From e37109184bfd7b9a104f409aa9fb780e0079dc49 Mon Sep 17 00:00:00 2001 From: "Jaldhar H. Vyas" Date: Mon, 15 Jul 2024 18:49:14 -0400 Subject: Challenge 121 part 2 by Jaldhar H. Vyas. --- challenge-121/jaldhar-h-vyas/perl/ch-2.pl | 42 +++++++++++++++++++++++++++++ challenge-121/jaldhar-h-vyas/raku/ch-2.raku | 29 ++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100755 challenge-121/jaldhar-h-vyas/perl/ch-2.pl create mode 100755 challenge-121/jaldhar-h-vyas/raku/ch-2.raku diff --git a/challenge-121/jaldhar-h-vyas/perl/ch-2.pl b/challenge-121/jaldhar-h-vyas/perl/ch-2.pl new file mode 100755 index 0000000000..e485088df4 --- /dev/null +++ b/challenge-121/jaldhar-h-vyas/perl/ch-2.pl @@ -0,0 +1,42 @@ +#!/usr/bin/perl +use v5.38; + +sub permute :prototype(&@) { + my $code = shift; + my @idx = 0..$#_; + while ( $code->(@_[@idx]) ) { + my $p = $#idx; + --$p while $idx[$p-1] > $idx[$p]; + my $q = $p or return; + push @idx, reverse splice @idx, $p; + ++$q while $idx[$p-1] > $idx[$q]; + @idx[$p-1,$q]=@idx[$q,$p-1]; + } +} + +my @matrix = map { [ split /\s+/, $_ ] } @ARGV; +my $minimumLength = "Inf"; +my @tour = (); + +my @permutations; +permute { push @permutations, \@_; } keys @{$matrix[0]}; + +for my $perm (@permutations) { + my $cost = 0; + my $from = 0; + + my @cities = grep { $_ != 0} @{$perm}; + for my $i (keys @cities) { + $cost += $matrix[$from]->[$cities[$i]]; + $from = $cities[$i]; + } + $cost += $matrix[$from]->[0]; + + if ($cost < $minimumLength) { + $minimumLength = $cost; + @tour = @cities; + } +} + +say "length = $minimumLength"; +say 'tour = (0 ', (join q{ }, @tour), ' 0)'; \ No newline at end of file diff --git a/challenge-121/jaldhar-h-vyas/raku/ch-2.raku b/challenge-121/jaldhar-h-vyas/raku/ch-2.raku new file mode 100755 index 0000000000..78d2b4e995 --- /dev/null +++ b/challenge-121/jaldhar-h-vyas/raku/ch-2.raku @@ -0,0 +1,29 @@ +#!/usr/bin/raku + +sub MAIN( + *@args +) { + my @matrix = @args.map({ [$_.words] }); + my $minimumLength = ∞; + my @tour = (); + for (@matrix[0].keys).permutations -> $perm { + my $cost = 0; + my $from = 0; + + my @cities = @$perm.grep({ $_ != 0}); + for @cities.keys -> $i { + $cost += @matrix[$from;@cities[$i]]; + $from = @cities[$i]; + } + $cost += @matrix[$from;0]; + + if $cost < $minimumLength { + $minimumLength = $cost; + @tour = @cities; + } + } + + say "length = $minimumLength"; + say 'tour = (0 ', @tour.join(q{ }), ' 0)'; +} + -- cgit