Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: Uninitialized warnings trouble

by hv (Prior)
on Dec 14, 2022 at 06:08 UTC ( [id://11148854]=note: print w/replies, xml ) Need Help??


in reply to Re: Uninitialized warnings trouble
in thread Uninitialized warnings trouble

Excellent, well done. :)

I see you are already writing quite different code from what you started with. Next it might be worth thinking about whether you can rearrange things to avoid having to repeat this block over and over:

{ $visible++; syswrite STDOUT, $forest[$current][$i] . 'V'; usleep 100000; next; }

Note also that you don't need syswrite STDOUT here, print is quite enough - you just need to set $| = 1; at the start to disable buffering.

For what it's worth, here is my version which uses almost the same approach:

#!/usr/bin/perl use strict; use warnings; use List::Util qw{ none any }; # parse the input (piped in, or from filename on command line) my @a = map { chomp; [ split // ] } <>; # determine the dimensions my $ni = @a; my $nj = @{ $a[0] }; # sanity check die "mismatched lengths" if any { @$_ != $nj } @a; # assume all visible to start with my $v = $ni * $nj; for my $i (0 .. $ni - 1) { for my $j (0 .. $nj - 1) { my $t = $a[$i][$j]; # target next if none { $_ >= $t } map $a[$i][$_], 0 .. $j - 1; # loo +k left next if none { $_ >= $t } map $a[$i][$_], $j + 1 .. $nj - 1; # loo +k right next if none { $_ >= $t } map $a[$_][$j], 0 .. $i - 1; # loo +k up next if none { $_ >= $t } map $a[$_][$j], $i + 1 .. $ni - 1; # loo +k down # if not visible in any direction, then invisible --$v; } } print "Visible $v of $ni x $nj\n";

If the speed of this algorithm ever becomes an issue, it also becomes interesting to consider a more dynamic approach: with a companion array of "visible/invisible" booleans, you can make just two passes over each row (once in each direction, or combined) and two over each column, then read the result out of the companion array. That reduces the algorithmic complexity from O(n^3) to O(n^2) for an n * n array.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11148854]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (9)
As of 2024-04-18 13:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found