in reply to 2 dimensional array

The table of letters search is a nice little problem. You may like to ponder the following solution:

use strict; use warnings; my $obj = bless {toDir => {qw(01 s 11 se 10 e 1-1 ne 0-1 n -1-1 nw -10 + w -11 s)}}; @{$obj}{'width', 'height'} = map {chomp; $_} split ',', <DATA>; for my $rowNum (1 .. $obj->{height}) { defined ($_ = <DATA>) or die "Fewer table rows than expected. Expected $obj->{height}, got +@{[$rowNum - 1]}"; chomp; push @{$obj->{table}}, [split '']; die "Short row given at row $rowNum" unless $obj->{width} == @{$ob +j->{table}[-1]}; } while (<DATA>) { chomp; push @{$obj->{wordList}}, split /,\s*/, uc; } for my $x (0 .. $obj->{width} - 1) { for my $y (0 .. $obj->{height} - 1) { $obj->explore ($x, $y); } } sub explore { my ($self, $x, $y) = @_; for my $word (@{$self->{wordList}}) { for my $xDelta (-1 .. 1) { for my $yDelta (-1 .. 1) { next if ! $xDelta and ! $yDelta; next unless $self->find ($word, $x, $y, $xDelta, $yDel +ta); my ($xPos, $yPos) = ($x + 1, $y + 1); print "Found '$word' starting at $xPos, $yPos and head +ing " . $self->{toDir}{"$xDelta$yDelta"} . "\n"; } } } } sub find { my ($self, $word, $x, $y, $xDelta, $yDelta) = @_; my $wordLen = length $word; return if $xDelta < 0 && $x - $wordLen < 0; return if $xDelta > 0 && $x + $wordLen >= $self->{width}; return if $yDelta < 0 && $y - $wordLen < 0; return if $yDelta > 0 && $y + $wordLen >= $self->{height}; return $self->search ($word, $x, $y, $xDelta, $yDelta) } sub search { my ($self, $word, $x, $y, $xDelta, $yDelta) = @_; my ($chr, $tail) = $word =~ /(.)(.*)/; my $tailLen = defined $tail ? length $tail : 0; return if $chr ne $self->{table}[$y][$x]; return 1 if $tailLen == 0; return $self->search ($tail, $x + $xDelta, $y + $yDelta, $xDelta, +$yDelta) } __DATA__ 15,10 ADESFJRASLXDFRT QBRAINOUEWHGYED RIRURLKUNGEASDV NAOBXCSTACHUIOL OJKDGKJGHJUINHR AHRHOAIDFSETRGH RXANOGSYEROGATS TOUDOGSDSAVFTRY UORTUOFRHRJUIKO BTIARTHYEUVFGQA Dogs, Cats Train

Prints:

Found 'DOGS' starting at 4, 5 and heading se Found 'DOGS' starting at 4, 8 and heading e Found 'CATS' starting at 10, 4 and heading w

Unless you can explain one or two Perl idioms like @{[$rowNum - 1]} you would be smart not to try and pass this off as your own work. ;)


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: 2 dimensional array
by mountain_drew (Initiate) on Jun 24, 2008 at 04:06 UTC
    way over my head but thanks for the effort. fortunately, the objective of the problem was to test my algorithm writing ability, not my perl writing ability. :)