Comment detail

文字列の八方向検索 (Nested Flatten)

This comment is reply for 4609 horiuchi: 素直に総当りで解いてみました。 enu...(文字列の八方向検索). Go to thread root.

すいません、連投になってしまいますが短い版を投稿させていただきます。チェック手抜き版です。

 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.ArrayList;
import java.util.List;

public class Sample99_2 {
    public enum Direction {
        左上(-1, -1),
        (0, -1),
        右上(1, -1),
        (1, 0),
        右下(1, 1),
        (0, 1),
        左下(-1, 1),
        (-1, 0);

        public final int dx_;
        public final int dy_;

        private Direction(int dx, int dy) {
            dx_ = dx;
            dy_ = dy;
        }
    }

    private final String[] matrix_;

    public Sample99_2(String[] matrix) {
        matrix_ = matrix;
    }

    public AnswerData[] search(String str) {
        List<AnswerData> result = new ArrayList<AnswerData>();
        char[] input = str.toCharArray();
        for (int y = 0; y < matrix_.length; y++) {
            for (int x = 0, maxX = matrix_[y].length(); x < maxX; x++) {
                for (Direction d: Direction.values()) {
                    if (search(input, x, y, d.dx_, d.dy_)) {
                        result.add(new AnswerData(x, y, d));
                    }
                }
            }
        }
        return result.toArray(new AnswerData[0]);
    }
    private boolean search(char[] input, int x, int y, int dx, int dy) {
        try {
            for (int index = 0; index < input.length; index++) {
                if (matrix_[y + dy * index].charAt(x + dx * index) != input[index]) {
                    return false;
                }
            }
            return true;
        } catch (IndexOutOfBoundsException ex) {
            return false;
        }
    }

    private static class AnswerData {
        public final int x;
        public final int y;
        public final Direction d;
        
        public AnswerData(int x, int y, Direction d) {
            this.x = x;
            this.y = y;
            this.d = d;
        }
    }

    public static void main(String[] args) {
        Sample99_2 s = new Sample99_2(new String[] {
                "リオウウリウ",
                "ウオリウオリ",
                "オリリオリウ",
                "リリオオウオ",
        });
        AnswerData[] datas = s.search("ウオリ");
        for (AnswerData d: datas) {
            System.out.format("(%d, %d), %s%n", d.x, d.y, d.d.name());
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...