challenge 文字列の八方向検索

与えられた矩形状の文字列中に存在する文字列"ウオリ"の位置を全て出力するプログラムを
書いてください。
文字列の検索方向は八方全てで、また連続している(左右や上下の境界をまたがない)ものを
対象とします。出力は起点"ウ"の座標と方向のリストにしてください。

サンプル入力:

リオウウリウ
ウオリウオリ
オリリオリウ
リリオオウオ

サンプル出力:

(2, 0), 左
(0, 1), 右
(0, 1), 下
(3, 1), 右
(4, 3), 左上

--
より一般には、任意の検索文字列への対応も考えてみてください。

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__

Index

Feed

Other

Link

Pathtraq

loading...