aboutsummaryrefslogtreecommitdiff
path: root/challenge-152
diff options
context:
space:
mode:
authorMichael Manring <michael@manring>2022-02-17 23:26:48 +0700
committerMichael Manring <michael@manring>2022-02-17 23:26:48 +0700
commitbc1a8f4f721d59cdde16c0d6265e7db9ff35bd07 (patch)
tree875ed71cd8f7c69795af7da38b6b013367620846 /challenge-152
parentc43f849dbadc6b057a01bdeae6813349d90abbf4 (diff)
downloadperlweeklychallenge-club-bc1a8f4f721d59cdde16c0d6265e7db9ff35bd07.tar.gz
perlweeklychallenge-club-bc1a8f4f721d59cdde16c0d6265e7db9ff35bd07.tar.bz2
perlweeklychallenge-club-bc1a8f4f721d59cdde16c0d6265e7db9ff35bd07.zip
accept accept input array in addition to script's argument, format output similar to examples of the challenge's task
Diffstat (limited to 'challenge-152')
-rw-r--r--challenge-152/pokgopun/perl/ch-1.pl55
1 files changed, 43 insertions, 12 deletions
diff --git a/challenge-152/pokgopun/perl/ch-1.pl b/challenge-152/pokgopun/perl/ch-1.pl
index ec75bb2919..a25c883896 100644
--- a/challenge-152/pokgopun/perl/ch-1.pl
+++ b/challenge-152/pokgopun/perl/ch-1.pl
@@ -1,18 +1,49 @@
+### Providing no argument, the script will use sample data similar to the examples in the challenge's task
+###
+### Example of usage: perl %scripl% 1 5,3 2,3,4 7,1,0,2 6,4,5,2,8
### Input: $triangle = [ [1], [5,3], [2,3,4], [7,1,0,2], [6,4,5,2,8] ]
-## Example of usage: perl %scripl% 1 5,3 2,3,4 7,1,0,2 6,4,5,2,8
+###
+### 1
+### 5 3
+### 2 3 4
+### 7 1 0 2
+### 6 4 5 2 8
+###
+### Output: 8
+###
+### Minimum Sum Path = 1 + 3 + 2 + 0 + 2 => 8
+##
#
use strict;
use warnings;
-#use Data::Dumper;
+use Data::Dumper;
-my $mins = "";
-while (@ARGV) {
- my $min = [sort { $a <=> $b } split(/\D/,shift)]->[0];
- # print Dumper $min;
- $mins .= "$min ";
+my @sample;
+### If scripts' arguments present, convert them to triangle array
+{
+ last unless @ARGV;
+ push @sample, [ map{[$_=~/(\d+)/g]} @ARGV ];
+}
+### Add sample triangle arrays if none available
+{
+ last if @sample;
+ push @sample, [ [1], [5,3], [2,3,4], [7,1,0,2], [6,4,5,2,8] ];
+ push @sample, [ [5], [2,3], [4,1,5], [0,1,2,3], [7,2,4,1,9] ];
+}
+#print Dumper \@sample;
+### Generate array of min path
+sub minPath {
+ my $path = shift;
+ my @minPath;
+ push @minPath, [sort { $a <=> $b } @$_]->[0] foreach @$path;
+ return @minPath
+}
+### Generate output similar to those in examples of the challenge's task
+foreach my $s (@sample) {
+ printf "\nInput: \$triangle = [ %s ]\n\n", join(", ", map{"[".join(",",@$_)."]"} @$s );
+ print "\t"," " x scalar(@{$s->[-1-$_]}), join(" ",@{$s->[$_]}),"\n" foreach 0..$#$s;
+ my @minPath = minPath($s);
+ my $sumText = join(" + ",@minPath);
+ my $sum = eval($sumText);
+ print "\nOutput: $sum\n\n\tMinimum Sum Path = $sumText => $sum\n",
}
-chop $mins;
-my $sum;
-$sum += $_ foreach split(/ /,$mins);
-$mins =~ s/ /+/g;
-print "Min Sum Path = $mins = $sum\n";