David Jagoe <davidja...@gmail.com> writes:

Hi David,

> Thanks! I had a nasty feeling that it could be done in a one-liner
> using partition-by or something similar. But of course you need to be
> able to look at previous elements...

Here's a slightly shorter variant.

--8<---------------cut here---------------start------------->8---
(defn partition-distinct [c]
  (reduce #(if (.contains (last %1) %2)
             (conj %1 [%2])
             (conj (subvec %1 0 (dec (count %1)))
                   (conj (last %1) %2)))
          [[]] (vec c)))
--8<---------------cut here---------------end--------------->8---

The difference is that it'll always return a vector of vectors, and of
course the .contains-check is linear for vectors, so it's quadratic to
the size of `c` in total.

If you don't care about the order of elements in each partition, then
you can just go with a vector of sets and have the same performance as
Cedric's recursive solution.

--8<---------------cut here---------------start------------->8---
(defn partition-distinct [c]
  (reduce #(if ((last %1) %2)
             (conj %1 #{%2})
             (conj (subvec %1 0 (dec (count %1)))
                   (conj (last %1) %2)))
          [#{}] (vec c)))
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to