Comment detail

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

"リリリ"の様な同じ文字が連続した文字列を検索すると不具合が出たので修正。 ついでに、何処まで行数を減らせるかテスト。可読性は二の次。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Program { //http://ja.doukaku.org/99/投稿用
    static void Main(string[] args) {
        string search = "ウオリ";
        System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>(new string[] { "リオウウリウ", "ウオリウオリ", "オリリオリウ", "リリオオウオ" });
        int width = list[0].Length; int height = list.Count;
        for(int y = 0; y < list.Count; y++) { //縦ループ
            for(int x = 0; x < list[y].Length; x++) { //横ループ
                for(int dx = -1; dx <= 1; dx++) { //左右方向ループ           -1は上、左 1は下、右を表す
                    for(int dy = -1; dy <= 1; dy = dy + (dx == 0 ? 2 : 1)) { //上下方向ループ 
                        try {                //dxが0の時はdyを2ステップして、両方が0にならないようにする                     
                            string strb = "";
                            for(int i = 0; i < search.Length; i++) { //iは移動量
                                strb += list[y + i * dy][x + i * dx];} //移動方向をdy,dxで乗算することで反転
                            if(search == strb) {
                                string directionStr = "";
                                if(dx < 0) directionStr += "左"; 
                                else if(dx > 0) directionStr += "右";
                                if(dy < 0) directionStr += "上";
                                else if(dy > 0) directionStr += "下";
                                System.Console.WriteLine("(" + x + "," + y + ")" + "," + directionStr);}
                        } catch(System.ArgumentOutOfRangeException) { } catch(System.IndexOutOfRangeException) { }}}}}
        System.Console.ReadLine();}}

「何処まで行数を減らせるか」に反応してつい書いてしまったので投稿。ついでに一行 80 文字で。あんまり無理はしてないつもりなんですが、可読性はこちらの方が低いかも……。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
(defun 8search (strings pattern)
  (loop with x = (length (elt strings 0)) and y = (length strings)
    with array = (make-array (list y x) :initial-contents strings)
    for (dx dy) in '((-1 -1) (-1 0) (-1 1) (0 -1) (0 1) (1 1) (1 0) (1 -1)) do
    (loop with m = (1- (length pattern))
      for a from (max 0 (- (* dx m))) below (min x (- x (* dx m))) do
      (loop for b from (max 0 (- (* dy m))) below (min y (- y (* dy m))) do
        (loop for i from a by dx and j from b by dy and c across pattern
          unless (char= c (aref array j i)) return nil finally
          (format t "(~D, ~D), ~[~;右~:;左~]~[~;下~:;上~]~%" a b dx dy))))))

(8search #("リオウウリウ" "ウオリウオリ" "オリリオリウ" "リリオオウオ")
         "ウオリ")

Index

Feed

Other

Link

Pathtraq

loading...