Thread Punkt in /auf Polygon (4 answers)
Opened by jan99 at 2010-08-23 12:08

MatthiasW
 2010-08-23 12:41
#140860 #140860
User since
2008-01-27
367 Artikel
BenutzerIn
[default_avatar]
Punkt in Polygon

Stupide nach Perl übersetzt:
Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package Polygon;

sub new { bless [@_[1..$#_]], ref $_[0] || $_[0] }

sub contains {
    my( $poly, $x, $y ) = @_;

    my $wn = 0;
    my( $x1, $y1 ) = @{ $poly->[-1] };
    my( $x2, $y2 ) = @{ $poly->[ 0] };

    my $start_over = $y1 >= $y;

    for ( 1 .. $#{ $poly } ) {
        my $end_over = $y2 >= $y;
        
        if ( $start_over != $end_over ) {
            if ( ($y2 - $y)*($x2 - $x1) <= ($y2 - $y1)*($x2 - $x) ) {
                $wn++ if $end_over;
            }
            else {
                $wn-- unless $end_over;
            }
        } # if

        $start_over = $end_over;
        ( $x1, $y1 ) = ( $x2, $y2 );
        ( $x2, $y2 ) = @{ $poly->[$_] };
    } # for

    return $wn != 0; # edit: war vorher $wn == 0, was natürlich falsch ist ;)
} # contains

Aufruf:
Code (perl): (dl )
1
2
3
4
5
my $polygon = Polygon->new( [5,5], [5,20], [20,20], [20,5], [5,5] ); # edit . durch , ersetzt

if ( $polygon->contains(10,10) ) {
    # 10,10 liegt im Polygon 5,5; 5,20; 20,20; 20,5; 5,5
} # if

edit: 2 Fehler korrigiert

MfG
Last edited: 2010-08-23 13:24:54 +0200 (CEST)
perl -E'*==*",s;;%ENV=~m,..$,,$&+42;e,$==f;$"++for+ab..an;@"=qw,u t,,print+chr;sub f{split}say"@{=} me"'

View full thread Punkt in /auf Polygon