[英]Iterate Clojure vectors
I am implementing a Clojure function (gol [coll])
that receives a vector of vectors of the same size with 1 and 0, iterates it checking the near positions of each index and returns a new board; 我正在实现一个Clojure函数(gol [coll])
,该函数接收一个大小为1和0的向量的向量,对其进行迭代以检查每个索引的附近位置并返回一个新的板; something like Conway's Game of Life 像康威的人生游戏
Input: 输入:
`(gol [[0 0 0 0 0]
[0 0 0 0 0]
[0 1 1 1 0]
[0 0 0 0 0]
[0 0 0 0 0]])`
Output: 输出:
`[[0 0 0 0 0]
[0 0 1 0 0]
[0 0 1 0 0]
[0 0 1 0 0]
[0 0 0 0 0]]`
How can I iterate the vectors and change the values at the same time? 如何迭代向量并同时更改值?
Use assoc-in
: 使用assoc-in
:
(assoc-in v [0 0] 1)
The above will set the top left value to 1
. 上面将左上角的值设置为1
。
To set many at once you can reduce over assoc-in
. 要一次设置多个,可以减少assoc-in
。
(def new-values [[[0 0] 1]
[[0 1] 2]
[[0 2] 3]])
(reduce
(fn [acc ele]
(apply assoc-in acc ele))
v
new-values)
;;=> [[1 2 3 0 0] ...]
To go from your input to your output the transform would be: 要从输入到输出,转换将是:
[[[2 1] 0]
[[2 3] 0]
[[1 2] 1]
[[3 2] 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.