Here's one I came up against on the weekend.

I have an object representing part of a space of N dimensions. This object has neighbours (e.g. if N is 1, it has 8 neighbours:

NNN
N*N
NNN

Now I need to get the co-ordinates of all my neighbours, assuming I have my own co-ordinates.

This seems to require setting up N nested for loops, each of them going for(-1,0,1){}. I couldn't think of an elegant way to do this, perhaps because I don't have a formal CS background.

In the end I produced a hack. NB, to understand this, you must realise that I only wanted my neighbours nearer the origin. Otherwise the hack would not have worked.

my $possibilities = 2 ** $N; # $N is number of dimensions # @mypos is my coordinates. for (1 .. $possibilities) { # using 0 would return my own position my $binary = sprintf '%b', $_; my $pad= '0' x ($N - length $binary); $binary = $pad.$binary; my @shift = split //, $binary; my @pos = map {$mypos[$_] - $shift[$_]} 0 .. $#mypos; push @neighbours, \@pos; }

This is neat but fundamentally evil, and I wondered if someone had a better solution. (Recursion?)

dave hj~


In reply to 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":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.