aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJaldhar H. Vyas <jaldhar@braincells.com>2024-07-15 18:49:14 -0400
committerJaldhar H. Vyas <jaldhar@braincells.com>2024-07-15 18:49:14 -0400
commite37109184bfd7b9a104f409aa9fb780e0079dc49 (patch)
tree1c921f2eb45d2dbbddff802c0b757c2e35d83627
parentc061337c22fed73627d23eafd49915b65039c0f5 (diff)
downloadperlweeklychallenge-club-e37109184bfd7b9a104f409aa9fb780e0079dc49.tar.gz
perlweeklychallenge-club-e37109184bfd7b9a104f409aa9fb780e0079dc49.tar.bz2
perlweeklychallenge-club-e37109184bfd7b9a104f409aa9fb780e0079dc49.zip
Challenge 121 part 2 by Jaldhar H. Vyas.
-rwxr-xr-xchallenge-121/jaldhar-h-vyas/perl/ch-2.pl42
-rwxr-xr-xchallenge-121/jaldhar-h-vyas/raku/ch-2.raku29
2 files changed, 71 insertions, 0 deletions
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)';
+}
+