How to compare values of consecutive elements in a vector for filtering?

  • A+
Category:Languages

I need to filter a given vector such that the output contains only those elements that are not a duplicate of an immediate neighbor.

Example : I/P -> [1 1 3 2 2 4 5 5]           O/P -> [3 4] 

 


This is exactly the same logic as @amalloy's answer, but it uses transducers instead of the threading macro (->>).

(defn isolate [coll]   (transduce    (comp    (partition-by identity)    (remove next)    (map first))   conj coll)) 

It should be more efficient, at least on large collections.

The partition-by identity partitions coll to sub-lists of identical elements. The remove next drops all sub-lists whose next is not nil (i.e., they have more than one element). The last map first takes the first element of each sub-list, thus flattening the list of lists to a list of elements.

Just run each of the steps separately to see how it works.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: