Search code examples
clojure

Sum equal adjacent integers


Test case:

(def coll [1 2 2 3 4 4 4 5])

(def p-coll (partition 2 1 coll))

;; ((1 2) (2 2) (2 3) (3 4) (4 4) (4 4) (4 5))

Expected output:

(2 2 4 4 4) => 16

Here is what I am to implement: Start with vector v [0]. Take each pair, if the first element of the pair is equal to the last element of the vector, or if the elements of the pair are equal, add the first item of the pair to v. (And finally reduce v to its sum.) The code below can do if the elements of the pair are equal part, but not the first part. (Thus I get (0 2 4 4). I guess the reason is that the elements are added to v at the very end. My questions:

  1. What is the way to compare an element with the last selected element?
  2. What other idiomatic ways are there to implement what I am trying achieve?
  3. How else can I approach the problem?
(let [s [0]]
  (concat s (map #(first %)
                 (filter #(or (= (first %) (first s)) (= (first %) (second %))) p-coll))))

Solution

  • You are on the right track with partitioning the data here. But there is a nicer way to do that. You can use (partition-by identity coll) to group consecutive, same elements.

    Then just keep the ones with more than one elements and sum them all up. E.g.

    (reduce 
      (fn [acc xs] 
        (+ acc (apply + xs))) 
      0 
      (filter 
        next 
        (partition-by identity coll)))