aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-064/mohammad-anwar/perl/ch-1.pl11
-rw-r--r--challenge-064/mohammad-anwar/perl/ch-1a.pl27
2 files changed, 25 insertions, 13 deletions
diff --git a/challenge-064/mohammad-anwar/perl/ch-1.pl b/challenge-064/mohammad-anwar/perl/ch-1.pl
index 9fad851e35..9e5cb47723 100644
--- a/challenge-064/mohammad-anwar/perl/ch-1.pl
+++ b/challenge-064/mohammad-anwar/perl/ch-1.pl
@@ -2,12 +2,21 @@
use strict;
use warnings;
+use List::Util qw(sum);
my $matrix = [[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]];
-print sprintf("%s\n", join " → ", @$_) for find_path($matrix, 0, 0);
+print min_sum_path($matrix, 0, 0), "\n";
+
+sub min_sum_path {
+ my ($matrix, $row, $col, $path) = @_;
+
+ my $paths = {};
+ $paths->{join " → ", @$_} = sum @$_ for find_path($matrix, 0, 0);
+ return (sort { $paths->{$a} <=> $paths->{$b} } keys %$paths)[0];
+}
sub find_path {
my ($matrix, $row, $col, $path) = @_;
diff --git a/challenge-064/mohammad-anwar/perl/ch-1a.pl b/challenge-064/mohammad-anwar/perl/ch-1a.pl
index cbfc232d11..1eb15002b2 100644
--- a/challenge-064/mohammad-anwar/perl/ch-1a.pl
+++ b/challenge-064/mohammad-anwar/perl/ch-1a.pl
@@ -4,21 +4,24 @@ use strict;
use warnings;
use Test::More;
-use Test::Deep;
-
-is_deeply([find_path([[ 1, 2, 3 ],
- [ 4, 5, 6 ],
- [ 7, 8, 9 ]],
- 0, 0)],
- [[ 1, 2, 3, 6, 9 ],
- [ 1, 2, 5, 6, 9 ],
- [ 1, 2, 5, 8, 9 ],
- [ 1, 4, 5, 6, 9 ],
- [ 1, 4, 5, 8, 9 ],
- [ 1, 4, 7, 8, 9 ]]);
+use List::Util qw(sum);
+
+is(min_sum_path([[ 1, 2, 3 ],
+ [ 4, 5, 6 ],
+ [ 7, 8, 9 ]],
+ 0, 0),
+ "1 → 2 → 3 → 6 → 9");
done_testing;
+sub min_sum_path {
+ my ($matrix, $row, $col, $path) = @_;
+
+ my $paths = {};
+ $paths->{join " → ", @$_} = sum @$_ for find_path($matrix, 0, 0);
+ return (sort { $paths->{$a} <=> $paths->{$b} } keys %$paths)[0];
+}
+
sub find_path {
my ($matrix, $row, $col, $path) = @_;
$path = [] unless defined $path;