我正在使用 Clojure 的 core.logic CLP(FD) 库(core.logic 版本 0.8.3)研究一个简单的平方打包算法。
正方形表示如下:
[[[x11 y11] [x12 y12]]
[[x21 y21] [x22 y22] ...]]
每个正方形表示为其左上角和右下角的坐标。
坐标是 FD 变量,在一定的区间内。
我想将解决方案的大小分别定义为距原点最近和最远的正方形的右上角和右下角之间的距离
(defne solution-size-o [size squares]
([s sqrs]
(fresh [closest farthest
x11 y11 x22 y22 _1 _2]
(closest-square [[x11 y11] _1] sqrs)
(farthest-square [_2 [x22 y22]] sqrs)
(project [x11 y11 x22 y22]
(let [a (- y22 y11)
b (- x22 x11)]
(== s (-> (+ (* a a) (* b b)) Math/sqrt Math/ceil int)))))))
这似乎适用于普通整数:
(run 1 [q]
(solution-size-o q [[[0 0] [1 1]] [[1 1] [2 2]]]))
=> (3)
即使是完全约束的 FD 变量
(defn constrained-solution-size []
(run 1 [q]
(fresh [size x11 y11
x12 y12
x21 y21
x22 y22 squares]
(fd/in x11 y11 x12 y12 x21 y21 x22 y22 (fd/interval 0 2))
(fd/eq
(= x11 0) (= y11 0) (= x21 1) (= y21 1)
(= x12 (+ x11 1)) (= y12 (+ y11 1))
(= x22 (+ x21 1)) (= y22 (+ y21 1)))
(== squares [[[x11 y11] [x12 y12]] [[x21 y21] [x22 y22]]])
(solution-size-o size squares)
(== q {:squares squares :size size}))))
(constrained-solution-size)
=> ({:squares [[[0 0] [1 1]] [[1 1] [2 2]]], :size 3})
但是,当变量的域没有受到完全约束时,它似乎会中断。例如,如果我删除 , 的约束y21 = 1
并且y11
在y21
其域中留下多个值:
(defn unconstrained-solution-size []
(run 1 [q]
(fresh [size x11 y11
x12 y12
x21 y21
x22 y22 squares]
(fd/in x11 y11 x12 y12 x21 y21 x22 y22 (fd/interval 0 2))
(fd/eq
(= x11 0) (= y11 0) (= x21 1)
(= x12 (+ x11 1)) (= y12 (+ y11 1))
(= x22 (+ x21 1)) (= y22 (+ y21 1)))
(== squares [[[x11 y11] [x12 y12]] [[x21 y21] [x22 y22]]])
(solution-size-o size squares)
(== q {:squares squares :size size}))))
我明白了
(unconstrained-solution-size)
=> ClassCastException clojure.core.logic.LVar cannot be cast to java.lang.Number clojure.lang.Numbers.minus (Numbers.java:135)
似乎project
只有当它们的域受到完全约束时才适用于 FD 变量。这是应该的吗?如果是,是否有人对如何对 FD 变量进行非关系算术有任何建议?
谢谢!