Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

(tye)Re: getting my neighbours in an N-dimensional space

by tye (Sage)
on Jan 21, 2002 at 20:42 UTC ( [id://140427]=note: print w/replies, xml ) Need Help??


in reply to getting my neighbours in an N-dimensional space

This version creates a closure that counts in base 3 using "digits" -1, 0, and 1, returning the next neighbor each time it is called. It returns "us" as one of our neighbors.

#!/usr/bin/perl -w use strict; use mapcar; sub neighbors { my @coords= @_; my @offset= (-1) x @coords; return sub { my $i= 0; return if ! @coords; my @return= mapcar { $_[0] + $_[1] } \@coords, \@offset; while( 1 < ++$offset[$i] ) { $offset[$i]= -1; if( $#offset < ++$i ) { @offset= @coords= (); last; } } return @return; }; } my $next= neighbors( 6, 2, -4 ); my @coords; while( @coords= $next->() ) { print "( @coords )\n"; }
produces:
( 5 1 -5 ) ( 6 1 -5 ) ( 7 1 -5 ) ( 5 2 -5 ) ( 6 2 -5 ) ( 7 2 -5 ) ( 5 3 -5 ) ( 6 3 -5 ) ( 7 3 -5 ) ( 5 1 -4 ) ( 6 1 -4 ) ( 7 1 -4 ) ( 5 2 -4 ) ( 6 2 -4 ) ( 7 2 -4 ) ( 5 3 -4 ) ( 6 3 -4 ) ( 7 3 -4 ) ( 5 1 -3 ) ( 6 1 -3 ) ( 7 1 -3 ) ( 5 2 -3 ) ( 6 2 -3 ) ( 7 2 -3 ) ( 5 3 -3 ) ( 6 3 -3 ) ( 7 3 -3 )

This was based on (tye)Re: Finding all Combinations and requires mapcar.

        - tye (but my friends call me "Tye")

Replies are listed 'Best First'.
Re:x2 getting my neighbours in an N-dimensional space
by grinder (Bishop) on Jan 21, 2002 at 20:58 UTC
    Oh well done! This is exactly what I was waffling on about. Except that as it stands, your code returns the point of origin, and the origin can't be a neighbour of itself.

    --
    g r i n d e r
    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u';

      Yeah, I mentioned that. Here is one that fixes that and is actually simpler. (:

      #!/usr/bin/perl -w use strict; use mapcar; sub neighbors { my @coords= @_; my @digits= ( 0, -1, 1 ); my @offset= (0) x @coords; return sub { my $i= 0; while( 2 < ++$offset[$i] ) { $offset[$i]= 0; return if $#offset < ++$i; } return mapcar { $_[0] + $digits[$_[1]] } \@coords, \@offset; }; } my $next= neighbors( 6, 2, -4 ); my @coords; while( @coords= $next->() ) { print "( @coords )\n"; }

              - tye (but my friends call me "Tye")

Log In?
Username:
Password:

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

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

    No recent polls found