如何通过在特定位置插入较小的子矩阵来更新表示为嵌套向量的大矩阵。
(def submatrix [[1 1] [1 1]])
(def matrix [[0 0 0] [0 0 0] [0 0 0]])
(def pos [1 1])
(defn update-matrix
"Returns new matrix with the submatrix inserted at the [x y] pos as
the top left position of the submatrix."
[matrix submatrix pos]
; implementation??
)
所需输出:(格式化以便于阅读)
[[0 0 0]
[0 1 1]
[0 1 1]]
到目前为止我的进展:
我可以在向量中更新子向量:
(def v [0 1 2 3 4 5 6])
(def subv ["x" "y" "z"])
(def pos 2)
(concat (take pos v) subv (drop (+ pos (count subv)) v)
; [0 1 "x" "y" "z" 5 6]
但我不知道从这里去哪里,或者最可能是最惯用的。
答案 0 :(得分:2)
您可以减少一系列更新坐标,在每个步骤中将一个项目从子矩阵复制到较大矩阵中的适当位置:
user> (defn update-matrix [matrix submatrix [y x]]
(reduce (fn [m [row col]]
(assoc-in m [(+ row y) (+ col x)]
(get-in submatrix [row col])))
matrix
(for [y (range (count submatrix))
x (range (count (first submatrix)))]
[y x])))
#'user/update-matrix
user> (update-matrix [[0 0 0] [0 0 0] [0 0 0]] [[1 1] [1 1]] [1 1])
[[0 0 0] [0 1 1] [0 1 1]]
答案 1 :(得分:2)
正确
我们可以将所需的功能定义为
(defn update-submatrix [m sub-m [x y]]
(replace-subvec
m
(map (fn [l r] (replace-subvec l r y)) (subvec m x) sub-m)
x))
... (replace-subvec v s start)
只要v
持续,start
将索引s
中的向量s
的元素替换为序列(replace-subvec (vec (range 10)) (range 3) 5)
; [0 1 2 3 4 0 1 2 8 9]
的元素。例如,
(defn replace-subvec [v s start]
(vec (concat (subvec v 0 start) s (subvec v (+ start (count s))))))
明确但缓慢的实施是
(def submatrix [[1 1] [1 1]])
(def matrix [[0 0 0] [0 0 0] [0 0 0]])
(def pos [1 1])
(update-submatrix matrix submatrix pos)
; [[0 0 0] [0 1 1] [0 1 1]]
...给出问题中的例子,
update-submatrix
加速
加快replace-subvec
的关键是加快(defn replace-subvec [v s start]
(loop [v (transient v), s s, i start]
(if (empty? s)
(persistent! v)
(recur (assoc! v i (first s)) (rest s) (inc i)))))
。
我们可以通过两种方式实现这一目标:
这给了我们
{{1}}
效果相同。
答案 2 :(得分:0)
这是我的15分钟。拍摄它:
(defn update-matrix
"Returns new matrix with the submatrix inserted at the [x y] pos as
the top left position of the submatrix."
[matrix submatrix pos]
(let [[x y] pos
height (count submatrix)
width (count (get submatrix 0))]
(loop [i 0 m matrix]
(if (< i height)
(let [item (vec (concat (vec (drop-last width (get matrix x))) (get submatrix i)))]
(recur (+ 1 i) (assoc m (+ i y) item)))
m))))
如果这不起作用,请告诉我。