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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |