aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad Sajid Anwar <Mohammad.Anwar@yahoo.com>2024-07-16 11:47:22 +0100
committerGitHub <noreply@github.com>2024-07-16 11:47:22 +0100
commit6486a41f698538f1e8f0fa8b3b3e01bb0cec0bb2 (patch)
tree8cab7b4eb5f4f275380a1fa57e786de23413d7c0
parentea65838314bb5eadb8cfbd1fd9677d4d1bd20d12 (diff)
parente37109184bfd7b9a104f409aa9fb780e0079dc49 (diff)
downloadperlweeklychallenge-club-6486a41f698538f1e8f0fa8b3b3e01bb0cec0bb2.tar.gz
perlweeklychallenge-club-6486a41f698538f1e8f0fa8b3b3e01bb0cec0bb2.tar.bz2
perlweeklychallenge-club-6486a41f698538f1e8f0fa8b3b3e01bb0cec0bb2.zip
Merge pull request #10443 from jaldhar/challenge-121
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)';
+}
+