A more Perlish cleaner version might look like:
use strict;
use warnings;
my @row = map {chomp; [split '']} <DATA>;
my $visible;
die "Data too awful to contemplate\n" if @row < 2 || @{$row[0]} < 2;
for my $col (1 .. $#{$row[0]} - 1) {
my $tHigh = $row[0][$col];
my $bHigh = $row[-1][$col];
$visible += 2; # Edge trees always visible
for my $depth (1 .. $#row - 1) {
test(\$tHigh, \$row[$depth][$col]) if $tHigh != 9;
test(\$bHigh, \$row[-$depth - 1][$col]) if $bHigh != 9;
last if $tHigh == 9 && $bHigh == 9;
}
}
for my $rowIdx (1 .. $#row - 1) {
# Count down from top edge
my $lHigh = $row[$rowIdx][0];
my $rHigh = $row[$rowIdx][-1];
$visible += 2; # Edge trees always visible
for my $depth (1 .. $#row - 1) {
test(\$lHigh, \$row[$rowIdx][$depth]) if $lHigh != 9;
test(\$rHigh, \$row[$rowIdx][-$depth - 1]) if $rHigh != 9;
last if $lHigh == 9 && $rHigh == 9;
}
}
$visible += 4; # We didn't consider the corners so do that now.
print $visible;
sub test {
my ($highest, $cell) = @_;
return if $$highest >= $$cell;
if ($$cell !~ /\./) {
++$visible;
$$cell .= '.';
}
$$highest = $$cell;
return $$highest == 9;
}
__DATA__
30373
25512
65332
33549
35390
which outputs 21 - the value suggested by the challenge. Note that is only deals correctly with rectangular forests containing 4 or more trees.
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|