Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active June 2, 2024 17:22
Show Gist options
  • Save PEZ/2cd6e7158b0ea3d24d125c997a0f8d1e to your computer and use it in GitHub Desktop.
Save PEZ/2cd6e7158b0ea3d24d125c997a0f8d1e to your computer and use it in GitHub Desktop.
Longest Increasing Sub-Seq – Rich 4Clojure Problem 53 – See: https://github.com/PEZ/rich4clojure
(ns rich4clojure.hard.problem-053
(:require [hyperfiddle.rcf :refer [tests]]))
;; = Longest Increasing Sub-Seq =
;; By 4Clojure user: dbyrne
;; Difficulty: Hard
;; Tags: [seqs]
;;
;; Given a vector of integers, find the longest
;; consecutive sub-sequence of increasing numbers. If two
;; sub-sequences have the same length, use the one that
;; occurs first. An increasing sub-sequence must have a
;; length of 2 or greater to qualify.
(def __ :tests-will-fail)
(comment
)
(tests
(__ [1 0 1 2 3 0 4 5]) := [0 1 2 3]
(__ [5 6 1 3 2 7]) := [5 6]
(__ [2 3 3 4 5]) := [3 4 5]
(__ [7 6 5 4]) := [])
;; To participate, fork:
;; https://github.com/PEZ/rich4clojure
;; Post your solution below, please!
@leonidUH
Copy link

(def __ (fn [coll] (let [predict #(= 1 (- (last %) (first %)))
                         result (map
                                  (comp set flatten (partial filter predict))
                                  (partition-by predict
                                                (partition-all 2 1 coll)))
                         result_map (group-by count result)
                         max_key (apply max (keys result_map))]
                     (vec (apply sorted-set (first (result_map max_key)))))))

@jsebdev
Copy link

jsebdev commented Jun 2, 2024

(defn get-consecutive-seq [sequence]
  (letfn [(reduce-fn [acc n]
            (let [last-item (last acc)]
              (if (= (inc last-item) n)
                (conj acc n)
                (reduced acc))))]
    (reduce reduce-fn [(first sequence)] (rest sequence))))

(defn __ [_seq]
  (let [initial-consecutive-seq (get-consecutive-seq _seq)
        initial-consecutive-seq-size (count initial-consecutive-seq)
        rest-seq (drop initial-consecutive-seq-size _seq)
        rest-consecutive-seq (get-consecutive-seq rest-seq)
        rest-consecutive-seq-size (count rest-consecutive-seq)]
    (->>
     (if (>= initial-consecutive-seq-size rest-consecutive-seq-size)
       initial-consecutive-seq
       rest-consecutive-seq)
     (#(if (> (count %) 1) % [])))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment