Skip to content

Instantly share code, notes, and snippets.

@will-clarke
Created September 11, 2018 06:56
Show Gist options
  • Save will-clarke/987815dadc1ba728d8052d8f83522ca5 to your computer and use it in GitHub Desktop.
Save will-clarke/987815dadc1ba728d8052d8f83522ca5 to your computer and use it in GitHub Desktop.
4clojure 53
;; Longest Increasing Sub-Seq - Hard
;; 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.
;; tags - seqs
;; restricted -
(ns offline-4clojure.p053
(:use clojure.test))
(defn consecutive-numbers
"can be reduced to a reduce call... :|"
([[h & t]] (consecutive-numbers t [h]))
([[h & t :as coll] acc]
;; (println "being called: coll: " coll " -- h: " h " -- t: " t " -- last-consecutive-numbers: " (first acc) " -- consecutive-numbers: " acc)
(if (= (inc (first acc)) h)
(consecutive-numbers t (cons h acc))
(reverse acc)
)
)
)
(defn mapped-consecutive-numbers
[coll]
(map-indexed
(fn [index x] (consecutive-numbers (drop index coll)))
coll
)
)
(defn max-consecutive-number
[coll]
(let [sorted (sort-by count (mapped-consecutive-numbers coll))
max-count (count (last sorted))
max-consecutive-numbers-coll (first (filter #(= (count %) max-count) sorted))
]
(if (= (count max-consecutive-numbers-coll) 1)
[]
max-consecutive-numbers-coll)
)
)
;; (defn take-while-incrementing [coll]
;; (take-while #(= (second %) (inc (first %))) coll)
;; )
;; (defn take-while-incrementing
;; ([[h & t]] (take-while-incrementing [h] t))
;; ([acc xs]
;; (reduce (fn [acc x]
;; ;; (println "------------")
;; ;; (println "acc "acc )
;; ;; (println "x "x)
;; ;; (println "last acc "(last acc))
;; ;; (println "first x - 1: "(dec x))
;; ;; (println "pred: " (= (last acc) (dec x)))
;; (if (= (last acc) (dec x))
;; (conj acc x)
;; acc
;; )
;; ) acc xs))
;; )
;; (defn stupid-doubler
;; ;; [1 2 3 4] => [[1] [1 2] [1 2 3] [1 2 3 4]] ??? HOW
;; [coll]
;; (let [mega-array (map (constantly coll) coll)]
;; (map-indexed #(take (inc %) %2) mega-array)
;; )
;; )
;; (defn longest-subsequence
;; ([coll]
;; (longest-subsequence coll [])
;; )
;; ([[h & t] longest-subseq-found]
;; )
;; )
(def __
max-consecutive-number
)
(defn -main []
(are [soln] soln
(= (__ [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]) [])
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment