in reply to getting my neighbours in an N-dimensional space
Your problem boils down to enumerating all the different combination of (-1, 0, 1) for each dimension, except that you need to omit (0, 0, 0, 0).
That is, for 4 dimensions, you want to iterate from (-1, -1, -1, -1), (-1, -1, -1, 0), (-1, -1, -1, 1), (-1, -1, 0, -1) ... all the way to (1, 1, 1, 1).Dominus is covering this sort of stuff in a book he is writing on advanced techniques in Perl. He describes a (relatively) simple method of doing this using closures, rather than using recursion. I can't point you directly to the web page, but if you consult his home node you'll find out how to get there.
Thinking about this, and refreshing my mind about what Dominus wrote concerning iterators, the following code does the trick (without using mapcar :). Although skipping over the origin is a bit of an ugly hack. Improvements welcomed.
#! /usr/bin/perl -w use strict; sub neighbourhood { my $dim = shift; my @current = (-1) x $dim; my $done = 0; return sub { return if $done; my @res = @current; my $i; ITER: for ($i = 0; $i < scalar @current; ++$i) { if (++$current[$i] > 1 ) { $current[$i] = -1; } else { my $not_origin = 0; ($current[$_] != 0 and $not_origin = 1) for @current; redo ITER unless $not_origin; last; } } $done = 1 if $i >= scalar @current; return @res; } } my $iter = neighbourhood( shift || 3 ); while( my @iter = $iter->() ) { print "@iter\n"; }
Hmm, since everyone else appears to be returning values based on the origin, I guess I should do so too. It is a simple enough matter (and will be more so in Perl 6, when @res ^+= @origin is legal).
--#! /usr/bin/perl -w use strict; sub neighbourhood { my @origin = @_; my $dim = scalar @origin; my @current = (-1) x $dim; my $done = 0; return sub { return if $done; my @res = @current; my $i; for ($i = 0; $i < scalar @current; ++$i) { $res[$i] += $origin[$i]; } ITER: for ($i = 0; $i < scalar @current; ++$i) { if (++$current[$i] > 1 ) { $current[$i] = -1; } else { my $not_origin = 0; ($current[$_] != 0 and $not_origin = 1) for @current; redo ITER unless $not_origin; last; } } $done = 1 if $i >= scalar @current; return @res; } } @ARGV = (6, 2, -4) unless @ARGV; my $iter = neighbourhood( @ARGV ); while( my @iter = $iter->() ) { print "@iter\n"; }
|
|---|