2014-09-04 25 views

回答

3

这似乎是康威的look-and-say sequence的发电机。

这将产生序列像

(1)    ; there is 1 "1" here, so... 
(1 1)   ; now there are 2 "1"s here, so... 
(2 1)   ; now there is 1 "2" and 1 "1" 
(1 2 1 1)  ; now there is 1 "1", 1 "2", and 2 "1"s, so... 
(1 1 1 2 2 1) ; now there are 3 "1"s, 2 "2"s, and 1 "1", so ... 
(3 1 2 2 1 1) ; etc. 

drop 1去除序列输出序列的输入序列,但由于也理所当然属于外观数列,我们可以将其删除。

我们有然后是(iterate look-say initial-seq)其中

(defn look-say [s] 
    (mapcat 
    (juxt count first) 
    (partition-by identity s))) 

所有迭代确实是早在喂函数的输出作为输入多次,产生中间结果的序列。

要了解look-sa​​y功能,请从里到外进行操作。我们从上面的示例输出的最后一行开始,作为一个很好的例子。

(def s '(1 1 1 2 2 1)) 

我们要组连续的重复

(def grouped-s (partition-by identity s)) 
grouped-s ;=> ((1 1 1) (2 2) (1)) 

然后 “说” 每一组的计数

(map count grouped-s) 
;=> (3 2 1) 

而且我们指望

​​3210

但我们宁愿得到点数和点数同时

(map (juxt count first) grouped-s) 
;=> ([3 1] [2 2] [1 1]) 

几乎有项目操作,只需要连接所有这些一起

(apply concat (map (juxt count first) grouped-s)) 
;=> (3 1 2 2 1 1) 

这是一样的

(mapcat (juxt count first) grouped-s) 
;=> (3 1 2 2 1 1) 

注意你也可以写为

(for [g (partition-by identity s) 
     f [count first]] 
    (f g)) 
;=> (3 1 2 2 1 1) 

W这可能会更清楚或有助于解释前者。