文字列の八方向検索
Posted feedbacks - D
参考にしたページに「境界チェックに頼ったプログラムを書くべきではありません」と書いてあったにもかかわらず、それに頼ってしまっています。
see: プログラミング言語 D
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 | import std.stdio;
class EightSearch {
private:
wstring[] m_matrix;
wstring m_keyword;
struct Direction {
int step_x;
int step_y;
wstring str;
}
static Direction[8] m_directions = [
{ step_x:1, step_y:0, str:"右" },
{ step_x:1, step_y:1, str:"右下" },
{ step_x:0, step_y:1, str:"下" },
{ step_x:-1, step_y:1, str:"左下" },
{ step_x:-1, step_y:0, str:"左" },
{ step_x:-1, step_y:-1, str:"左上" },
{ step_x:0, step_y:-1, str:"上" },
{ step_x:1, step_y:-1, str:"右上" } ];
/* ある場所のある方向について探索 */
void search_one(int start_y, int start_x, Direction d) {
try {
int tmp_x = start_x;
int tmp_y = start_y;
for (int i = 0; i < m_keyword.length; ++i) {
if (m_keyword[i] != m_matrix[tmp_y][tmp_x]) {
return;
}
tmp_x += d.step_x;
tmp_y += d.step_y;
}
/* 見つけた! */
writefln("(%d, %d), %s", start_x, start_y, d.str);
}
catch (Exception) {
}
}
public:
this(wstring[] m, wstring k) {
m_matrix = m;
m_keyword = k;
}
/* 全ての場所の全ての方向について探索 */
void search_all() {
for (int i = 0; i < m_matrix.length; ++i) {
for (int j = 0; j < m_matrix[0].length; ++j) {
if (m_keyword[0] != m_matrix[i][j]) {
continue;
}
foreach (k; m_directions) {
search_one(i, j, k);
}
}
}
}
}
/*
void main() {
static wstring[] m = [
"リオウウリウ",
"ウオリウオリ",
"オリリオリウ",
"リリオオウオ"];
static wstring k = "ウオリ";
EightSearch es = new EightSearch(m, k);
es.search_all();
}
*/
|



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