From 6c4319b9b87a87ea03c7d4dc75fbf7b7f4c84797 Mon Sep 17 00:00:00 2001 From: drbaggy Date: Wed, 17 Feb 2021 04:39:53 +0000 Subject: Some notes on the display function --- challenge-100/james-smith/perl/ch-2.pl | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'challenge-100') diff --git a/challenge-100/james-smith/perl/ch-2.pl b/challenge-100/james-smith/perl/ch-2.pl index f46b12cf6f..a2f18d481e 100644 --- a/challenge-100/james-smith/perl/ch-2.pl +++ b/challenge-100/james-smith/perl/ch-2.pl @@ -60,23 +60,28 @@ sub triangle_sum_1point5_liner { $b->[0]; } +## A subroutine to display the triangle indicating the route! sub display_sum { - my @tri = @_; - my @route; + my @tri = map{ [@{$_}] } @_; ## Deep copy the triangle as the search is destructive + my @route; ## For each node in the "current" bottom row, the route is the list + ## of indecies of the child nodes that make up the "optimal" path + ## use implicit my on $b.... while(@{$b = pop @tri}>1) { ($tri[-1][$_],$route[$_]) = $b->[$_]<$b->[$_+1] ? ( $tri[-1][$_] + $b->[$_], [$_, @{$route[$_ ]||[]}] ) : ( $tri[-1][$_] + $b->[$_+1], [$_+1,@{$route[$_+1]||[]}] ) foreach 0..@tri-1; } - @route = (0,@{$route[0]}); - print + @route = (0,@{$route[0]}); ## We need to add the top node index (always 0) + ## At the same time we can just take the first (only) + ## path out of the 2d route matrix; + print ## Assume all cell numbers are single digits... '', ( map { - ' ' x (@_-($a=$_)), + ' ' x (@_-($a=$_)), ## use implicit my on $a; ( map { sprintf $route[$a]==$_ ? '[%d] ': ' %d ' , $_[$a][$_] } 0..$a ), "\n" } 0..@_-1 ), - "\n"; + "\nMinimum path: ",$b->[0],"\n\n"; } -- cgit