【发布时间】:2017-02-15 21:36:59
【问题描述】:
我想在 Clojure 中为棋盘游戏表示 2D 位置 + 邻居的图表。我正在使用将位置映射到邻居向量的地图:
{[0 0] [[0 1] [1 0] [1 1]]}
我编写了一些函数,可以为任何大小的棋盘生成邻居图:
(defn positions [size]
(for [x (range 0 size) y (range 0 size)] [x y]))
(defn neighbors [size [x y]]
(filter (fn [[x y]]
(and (>= x 0) (< x size) (>= y 0) (< y size)))
(-> []
(conj [(inc x) y])
(conj [(dec x) y])
(conj [x (inc y)])
(conj [x (dec y)])
(conj [(inc x) (inc y)])
(conj [(dec x) (dec x)]))))
(defn board-graph
[size]
(reduce (fn [map position] (assoc map
position
(neighbors size position)))
{}
(positions size)))
这很好用:
(board-graph 2)
=> {[0 0] ([1 0] [0 1] [1 1]), [0 1] ([1 1] [0 0]), [1 0] ([0 0] [1 1] [0 0]), [1 1] ([0 1] [1 0] [0 0])}
然而我现在想在棋盘边缘的每个棋盘位置添加这个额外的“虚拟邻居”,例如:TOP、:BOTTOM、:LEFT、:对。所以我想:
(board-graph 2)
=> {[0 0] (:LEFT :TOP [1 0] [0 1] [1 1]), [0 1] (:LEFT :BOTTOM [1 1] [0 0]), [1 0] (:RIGHT :TOP [0 0] [1 1] [0 0]), [1 1] (:RIGHT :BOTTOM [0 1] [1 0] [0 0])}
到目前为止,这是我的尝试,但效果不太好,而且看起来确实过于复杂:
(defn- filter-keys
[pred map]
(into {}
(filter (fn [[k v]] (pred k)) map)))
(defn board-graph
[size]
(let [g (reduce (fn [map position] (assoc map
position
(neighbors size position)))
{}
(positions size))]
(merge g
(reduce-kv #(assoc %1 %2 (conj %3 :TOP)) {}
(filter-keys (fn [[x y]] (= y 0)) g))
(reduce-kv #(assoc %1 %2 (conj %3 :BOTTOM)) {}
(filter-keys (fn [[x y]] (= y (dec size))) g))
(reduce-kv #(assoc %1 %2 (conj %3 :LEFT)) {}
(filter-keys (fn [[x y]] (= x 0)) g))
(reduce-kv #(assoc %1 %2 (conj %3 :RIGHT)) {}
(filter-keys (fn [[x y]] (= x (dec size))) g)))))
我基本上想构建我的地图,再次查看它,并为某些键更新关联的值,具体取决于键是什么。如果不诉诸状态,我找不到一个很好的方法! 有没有更惯用的方式来做到这一点?
【问题讨论】:
-
你熟悉update吗?
-
谢谢。虽然更新仅适用于单个键。我基本上有 4 个需要调用更新的键列表。考虑到我改变了我的搜索并发现了这个:stackoverflow.com/questions/9638271/…这可能会修复代码的最后一部分。
标签: clojure