文字列の八方向検索
Posted feedbacks - Perl
オーソドックスな総当たり。
Dan the Perl Monger
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #!/usr/local/bin/perl
use strict;
use warnings;
use utf8;
my %direction = (
上 => [0, -1], 右上 => [ 1, -1], 右 => [ 1, 0], 右下 => [ 1, 1],
下 => [0, 1], 左下 => [-1, 1], 左 => [-1, 0], 左上 => [-1, -1]
);
sub search8 {
my @word = split //, shift;
my @field = map { chomp; [ split //, $_ ] } split /[\r\n]+/, shift;
my @result;
for my $y ( 0 .. @field - 1 ) {
for my $x ( 0 .. @{ $field[$y] } - 1 ) {
# warn join(",", $x, $y, $field[$y][$x]);
LOOP: for my $d ( sort keys %direction ) {
my $lx = $x;
my $ly = $y;
for my $c (@word) {
next LOOP if $lx < 0 || $lx >= @{ $field[$y] };
next LOOP if $ly < 0 || $ly >= @field;
next LOOP if $field[$ly][$lx] ne $c;
$lx += $direction{$d}->[0];
$ly += $direction{$d}->[1];
}
push @result, "($x, $y), $d";
}
}
}
@result;
}
$\ = "\n";
binmode STDOUT => ':utf8';
print join "\n", search8( 'ウオリ', <<"EOT");
リオウウリウ
ウオリウオリ
オリリオリウ
リリオオウオ
EOT
__END__
|


kuromin #4400() Rating0/2=0.00
[ reply ]