[kw-pm] Mystery code!

Daniel R. Allen da at coder.com
Fri Sep 17 17:07:29 CDT 2004


On Fri, 17 Sep 2004, Eric - fishbot wrote:

> It seems that using a 2D array, it would be fairly easy to
> determine adjacency... anything that is +-[1|0,1|0] away.  If you
> pushed these adjacencies into an hashofArray, then a [triple]
> nested loop can create the regex of non-adjacencies.

I'm convinced the right way to show the adjacencies is to just list them
outright; for the 3x3 grid we looked at, any generative way is overkill.
For bigger grids, the right way is probably the one you just described,
but that's got nothing to do with a phone keypad. :->

Another solution would be a finite state machine, but that's REALLY
overkill.

> # given %adjacent{$i} is array of numbers adjacent to $i:
>
> my @illegal_pairs;
>
> for my $i ( 2..9 ) {
>     INNER: for my $j ( 2..9 ) {
>         next INNER if (( $i == $j ) ||
>                        ( grep { $_ == $j } @{$adjacent{$i}} ));
>         push @illegal_pairs, "$i$j";
>     }
> }
>
> my $regex = join "|", @illegal_pairs;


a hash of hashes is just as easy to set up as a hash of arrays, and if
%adjacent{$i} is a hash of numbers adjacent to $i, you can get rid of the
grep:

    next INNER if (( $i == $j ) || $adjacent{$i}{$_} ));

hm, since you can't stay on the same key twice, shouldn't ($i == $j) be an
illegal move also?

    next INNER if ($adjacent{$i}{$_});

So that collapses to:

for my $i (2..9) {
    for my $j (2..9) {
        next unless ($adjacent{$i}{$j});
        push @illegal_pairs, "$i$j";
    }
}

but wait- that looks like a grep:

push @illegal_pairs, grep { ! $adjacent{$i}{$_} } for my $i (2..9);

> Perhaps someone can come up with a sexy map{} for the problem?

Settle for a sexy grep?... assuming I set it up properly, which is
never a sure thing.

And now the only messy part is setup. :-)

-Daniel

--
http://coder.com/ - Prescient Code Solutions - (519) 575-3733 da at coder.com

>
> Eric




More information about the kw-pm mailing list