Friday, January 17, 2014

99 Clojure Problems – 8: Eliminate Consecutive Duplicates of List Elements

Example:

(deftest p08-compress
  (is (= '[a b c a d e]  (compress  '[a a a a b c c a a d e e e e]))))

Solution:

Source

A simple reduce that only conjoins the current element to the result if it is not identical to its predecessor. It uses last to find out who that predecessor was. This is not the most efficient way to solve the problem, as we know from problem 1, last has linear time complexity.

Read more about this series.

2 comments:

WranglerAz said...

I stumbled upon this page while looking for an understanding of the same problem.

While I was looking through your compress, which uses last, I also found a solution using first.

( #(map first (partition-by identity %)) '[a a a a b c c a a d e e e e])

I am still learning so I have no idea which way is preferred, do you have an opinion?

pbrc said...

@WranglerAz I like your solution it performs better than mine because 'last' takes linear time. Also your solution is way more elegant and succinct.