这样做的最佳方法是什么?这是我到目前为止所得到的
(defn line-segment [start end]
(let [x-direction (abs (- (first end) (first start)))
y-direction (abs (- (last end) (last start)))]
(cond
(= 0 x-direction) (something ...)
(= 0 y-direction) (something ...))))
这是我的最终目标
user=> (line-segment [5 6] [5 8])
([5 6] [5 7] [5 8])
是的,没有对角线,只有x或y移动。
感谢。
答案 0 :(得分:2)
我认为这是一个非常优雅的解决方案:
(defn line-segment [start end]
(let [x1 (first start) x2 (first end)
y1 (last start) y2 (last end)
dx (if (> x1 x2) -1 1)
dy (if (> y1 y2) -1 1)]
(for [x (range x1 (+ dx x2) dx)
y (range y1 (+ dy y2) dy)]
[x y])))
REPL会议:
user> (line-segment [5 6] [5 8])
([5 6] [5 7] [5 8])
user> (line-segment [5 8] [5 6])
([5 8] [5 7] [5 6])
user> (line-segment [-2 7] [1 7])
([-2 7] [-1 7] [0 7] [1 7])
user> (line-segment [1 7] [-2 7])
([1 7] [0 7] [-1 7] [-2 7])
即使您的示例输出被格式化为向量,此函数也会返回LazySeq
。我认为这并不重要。
答案 1 :(得分:0)
这是一个简单的解决方案,也允许对角线:
(use 'clojure.contrib.math)
(defn line-segment [start end]
(let [x1 (first start) x2 (first end)
y1 (last start) y2 (last end)
xdiff (- x2 x1)
ydiff (- y2 y1)
maxdiff (max (abs xdiff) (abs ydiff))
dx (/ xdiff maxdiff)
dy (/ ydiff maxdiff)]
(for [i (range (inc maxdiff))]
[(round (+ x1 (* i dx))) (round (+ y1 (* i dy)))])))
与dbryne的解决方案一样,这会返回一个懒的点序列而不是一个向量:我认为这是最有用的形式,假设您随后想要依次对线段上的每个点执行某些操作。