2012-07-19 87 views
2

我需要一个函数来计算序列中连续相等条目的数量。例如,(连续的“abcdefg”)应该返回0,而(连续的“aabcdddefg”)应该返回3.Clojure:连续重复项的数量

是我写它的习惯用法还是可以改进?

(defn consecutive [p] 
    (second (reduce 
      #(vector %2 
        (if (= (first %1) %2) 
         (inc (second %1)) 
         (second %1))) 
      [nil 0] 
      p))) 

回答

4
user> (defn consecutive [s] (->> s (partition-by identity) (reduce #(+ % (dec (count %2))) 0))) 
#'user/consecutive 
user> (consecutive "abcdefg") 
0 
user> (consecutive "aabcdddefg") 
3 

我更喜欢(partition-by identity)成语时,需要一些连续序列。

1

试试这个。

(defn consecutive [string] 
    (let [n (apply max (map count (partition-by identity string)))] 
    (if (= n 1) 0 n))) 

这是常见的模式

5

我认为(consecutive "abcdefg")应该返回1,不是0

这里有一个简单的实现,实现了这一点:

(defn consecutive [s] 
    (apply max (map count (partition-by identity s)))) 
+1

为什么要'(连续的“ABCDEFG “)'返回1?你能否详细说明一下? – 2012-07-19 15:29:04

+1

因为最长的连续字符序列是长度为1(单个字符)。在这种情况下强迫结果为零似乎逻辑上不一致。我认为唯一的情况是你有零个连续的字符是一个空字符串。 – mikera 2012-07-19 16:24:56