aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWalt Mankowski <waltman@pobox.com>2020-09-21 21:05:05 -0400
committerWalt Mankowski <waltman@pobox.com>2020-09-21 21:05:05 -0400
commitb503151a14318f0a18b4d27d561612537eca3ae4 (patch)
tree420946eba47c6de5033da43b5a9baf39517bc019
parent96602a860bf1744e423f0d41222ff82d70812c0f (diff)
downloadperlweeklychallenge-club-b503151a14318f0a18b4d27d561612537eca3ae4.tar.gz
perlweeklychallenge-club-b503151a14318f0a18b4d27d561612537eca3ae4.tar.bz2
perlweeklychallenge-club-b503151a14318f0a18b4d27d561612537eca3ae4.zip
perl code for challenge 79 task 2
-rw-r--r--challenge-079/walt-mankowski/perl/ch-2.pl54
1 files changed, 54 insertions, 0 deletions
diff --git a/challenge-079/walt-mankowski/perl/ch-2.pl b/challenge-079/walt-mankowski/perl/ch-2.pl
new file mode 100644
index 0000000000..5a58052c37
--- /dev/null
+++ b/challenge-079/walt-mankowski/perl/ch-2.pl
@@ -0,0 +1,54 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use feature qw(:5.32);
+use experimental qw(signatures);
+use List::Util qw(max);
+
+# TASK #2 › Trapped Rain Water
+# Submitted by: Mohammad S Anwar
+#
+# You are given an array of positive numbers @N.
+#
+# Write a script to represent it as Histogram Chart and find out how
+# much water it can trap.
+
+my @a = @ARGV;
+
+# build the histogram
+my $rows = max(@a);
+my $cols = @a;
+my @hist;
+for my $col (0..$#a) {
+ for my $row (0..$rows-1) {
+ $hist[$row][$col] = $row < $a[$col] ? 1 : 0;
+ }
+}
+
+my $units = 0;
+for my $row (1..$rows-1) {
+ for my $col (1..$cols-1) {
+ $units++ if trapped($row, $col, $cols, @hist);
+ }
+}
+
+say $units;
+
+sub trapped($row, $col, $max_col, @hist) {
+ # check if we're at a wall
+ return 0 if $hist[$row][$col];
+
+ # look for left wall
+ my $left = 0;
+ for (my $c = $col-1; $c >= 0 && !$left; $c--) {
+ $left = 1 if $hist[$row][$c];
+ }
+
+ # look for right wall
+ my $right = 0;
+ for (my $c = $col+1; $c < $max_col && !$right; $c++) {
+ $right = 1 if $hist[$row][$c];
+ }
+
+ return $left && $right;
+}