Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Finding object perimeter

by gryphon (Abbot)
on Apr 16, 2002 at 22:05 UTC ( [id://159644]=note: print w/replies, xml ) Need Help??


in reply to Finding object perimeter

Greetings "Anonymous Monk",

First of all, this sounds very much like a homework assignment. If so, then I'm going to feel bad for helping you out. If not, then in the future, you may want to post code that you're working on or examples of what you've tried. Folks here are much more interested to help out when they feel like they're helping, not doing.

With that said, here's what I've come up with: I wasn't really sure what you meant by "perimeter", so I assumed that you mean if the area where the "x"s are is a box or an object in 2-D space, what's the perimeter of that object assuming that each character has a width of 1. If that's the case, try the following:

#!/usr/bin/perl -w use strict; my $obj1 = <<ENDOFOBJ; .... .xx. .xx. .... ENDOFOBJ my $obj2 = <<ENDOFOBJ; ...... .xx... .xxxx. ..xxx. ...... ENDOFOBJ my $obj = \$obj2; my $perimeter; foreach (split /\n/, $$obj) { $perimeter++ while /(?=\.x|x\.)/g; } my @lines; foreach (split /\n/, $$obj) { push @lines, [ split '' ]; } my @new_lines; for (my $y=0; $y <= $#lines; $y++) { for (my $x=0; $x <= $#lines; $x++) { $new_lines[$y] .= $lines[$x][$y]; } } foreach (@new_lines) { $perimeter++ while /(?=\.x|x\.)/g; } print $perimeter; exit;

Essentually, I first just start counting the number of times an "x" is next to a "." horizontally. That's easy. Then I run a split on each character and dump them into an array of arrays which is then worked through vertically and scanned for "perimeter breaks" as before.

Standard disclaimer: While this code seems to work in the test cases I've thrown at it, the code was written rather rapidly while on drugs for a sinus infection. Consequently, there most certainly is a better way to do this. merlyn, for example, would be able to do this in a single line with a bunch of maps and splits and stuff, I suspect.

-gryphon
code('Perl') || die;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-26 00:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found