作者Schelfaniel (Schelfaniel)
看板Programming
标题Re: [问题] 递回改非递回
时间Sun Apr 18 21:44:07 2010
用 Clojure 改写 :QQ
; 边是否在点上?
(defn other-point [point edge]
(cond
(= point (first edge)) (second edge)
(= point (second edge)) (first edge)
:else nil))
; 列印一笔划,假设是全双向边
; point : 初期点
; edges : 边,格式 [['1 '2] ['1 '3] ['1 '5]]
; history : 历史,初期为 nil
(defn stretch-single-line0 [point edges history]
(if (empty? edges)
(println (apply str (reverse (cons point history))))
(doseq [edge (filter #(other-point point %) edges)]
(stretch-single-line (other-point point edge)
(remove #(= edge %) edges) (cons point history)))))
; 非递回格式
(defn stretch-single-line1 [point edges]
(loop [stack (list (list point edges nil))]
(when-not (empty? stack)
(let [[point edges history] (first stack)
stack (rest stack)]
(if (nil? (first edges))
(do
(println (apply str (reverse (cons point history))))
(recur stack))
(let [items (map #(list (other-point point %)
(remove (partial = %) edges) (cons point history))
(filter #(other-point point %) edges))]
(recur (into stack (reverse items)))))))))
; 测试用函式
(defn test0 []
(stretch-single-line0 '1 [['1 '2] ['1 '3] ['1 '5] ['2 '3]
['2 '5] ['3 '4] ['3 '5] ['4 '5]] nil))
(defn test1 []
(stretch-single-line1 '1 [['1 '2] ['1 '3] ['1 '5] ['2 '3]
['2 '5] ['3 '4] ['3 '5] ['4 '5]]))
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.32.74.159