aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSteven Wilson <steven1170@zoho.eu>2020-09-24 14:46:52 +0100
committerSteven Wilson <steven1170@zoho.eu>2020-09-24 14:46:52 +0100
commita4db48b4f406664028abed832272098338cc65fa (patch)
tree5a9f8f19f9ed6b2c317498cfc41106a484e233e3
parent2219aec5c27fb1757c5cde240adf6c0fa5231179 (diff)
downloadperlweeklychallenge-club-a4db48b4f406664028abed832272098338cc65fa.tar.gz
perlweeklychallenge-club-a4db48b4f406664028abed832272098338cc65fa.tar.bz2
perlweeklychallenge-club-a4db48b4f406664028abed832272098338cc65fa.zip
add solution week 79 task 2
-rw-r--r--challenge-079/steven-wilson/perl/ch-2.pl44
1 files changed, 44 insertions, 0 deletions
diff --git a/challenge-079/steven-wilson/perl/ch-2.pl b/challenge-079/steven-wilson/perl/ch-2.pl
new file mode 100644
index 0000000000..58b775bfe8
--- /dev/null
+++ b/challenge-079/steven-wilson/perl/ch-2.pl
@@ -0,0 +1,44 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use feature qw/ say /;
+use List::Util qw/ sum max /;
+use Test::More;
+
+my @N1_t = ( 2, 1, 4, 1, 2, 5 );
+my @N2_t = ( 3, 1, 3, 1, 1, 5 );
+ok( water_trapped( \@N1_t ) == 6 );
+ok( water_trapped( \@N2_t ) == 6 );
+done_testing();
+
+sub water_trapped {
+ my $input_ref = shift;
+ my @input = @{$input_ref};
+ my $hist_width = scalar @input;
+ my $hist_height = max(@input);
+ my $total_water_trapped;
+
+ for my $row ( 2 .. $hist_height ) {
+ my @row_array;
+ for my $column ( 0 .. $hist_width - 1 ) {
+ if ( $input[$column] >= $row ) {
+ $row_array[$column] = 0;
+ }
+ else {
+ $row_array[$column] = 1;
+ }
+ }
+ if ( !( sum(@row_array) == $hist_width - 1 ) ) {
+ while ( $row_array[0] == 1 ) {
+ shift @row_array;
+ }
+ while ( $row_array[-1] == 1 ) {
+ pop @row_array;
+ }
+ $total_water_trapped += sum(@row_array);
+ }
+ }
+ return $total_water_trapped;
+}
+