Here is a solution to the problem:
# read in matrix
while (<DATA>) {
next if /^\s*$/;
push @r, [split];
}
# find the boundaries
for my $r (0..@r-1) {
for my $c (0..@{$r[0]}-2) {
$vert[$r][$c] = $r[$r][$c] ne $r[$r][$c+1] ? 1 : 0;
}
}
for my $r (0..@r-2) {
for my $c (0..@{$r[0]}-1) {
$horz[$r][$c] = $r[$r][$c] ne $r[$r+1][$c] ? 1 : 0;
}
}
for my $r (0..@r-2) {
for my $c (0..@{$r[0]}-2) {
$cross[$r][$c] = $vert[$r][$c] + $vert[$r+1][$c]
+ $horz[$r][$c] + $horz[$r][$c+1] > 1 ? 1 : 0;
}
}
# Print it out
for my $r (0..@r-1) {
for my $c (0..@{$r[0]}-1) {
print $r[$r][$c];
print $vert[$r][$c] ? '|' : ' ' if $c < @{$r[0]}-1;
}
print "\n";
next unless $r < @r-1;
for my $c (0..@{$r[0]}-1) {
print $horz[$r][$c] ? '-' : ' ' ;
print $cross[$r][$c] ? '+' : ' ' if $c < @{$r[0]}-1;
}
print "\n";
}
__DATA__
P P B R B
P R B B B
B R R R B
B R R R B
B G G B B
I have simplified the printing to just put a cross at all intersections, you can easily generalize to vertical and horizontal connections, etc. I'll leave the conversion to Fortran 1-based matrices to you :-)
Update: If efficiency is a concern, the three passes to find the boundary can be combined into one with a little extra logic. For large matrices, this change may blow the cache fewer times.
-
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.
|