Hi,

On Jan 28, 7:26 am, braver <delivera...@gmail.com> wrote:
> I'd like to partition a positive numeric sequence into subsequences so
> that each increasing subsequence is the longest possible among its
> neighbors.  Here's the closest I got so far:
>
> (use 'clojure.contrib.seq-utils)
> (defn clis [s] (->> s (into [-1]) (partition 2 1) (partition-by (fn
> [[x y]] (< x y))) (map #(map second %))))
>
> -1 here plays the role of minus infinity.  Prepending it with into
> assumes we supply the original sequence as a vector; would be nice to
> relax that and allow either a seq or a vector.  Here's a sample
> output:
>
> (clis [3 2 1 2 3 0 1 2 3 4 0 1 1 2])
> => ((3) (2 1) (2 3) (0) (1 2 3 4) (0) (1) (1) (2))
>
> In between decreasing and increasing, it assigns the middle element
> wrongly.  Reassigning it via an elaborate (partition 2 ...) with
> regluing between halves seems too heavy...  Anything smarter?

lazy-seq to the rescue:

user=> (defn clis
         [coll]
         (letfn [(step
                   [prev s]
                   (let [fst (first s)
                         lst (peek prev)]
                     (if (or (nil? s) (and lst (<= fst lst)))
                       (cons prev (clis s))
                       (recur (conj prev fst) (next s)))))]
           (lazy-seq
             (when-let [s (seq coll)]
               (step [] s)))))

user=> (clis [3 2 1 2 3 0 1 2 3 4 0 1 1 2])
([3] [2] [1 2 3] [0 1 2 3 4] [0 1] [1 2])

Hope this helps.

Sincerely
Meikel

-- 
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