Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

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")

In reply to (tye)Re: getting my neighbours in an N-dimensional space by tye
in thread getting my neighbours in an N-dimensional space by dash2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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 or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2021-05-12 15:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (129 votes). Check out past polls.

    Notices?