Created
September 15, 2021 04:42
-
-
Save samboozle/e4f2de4beafd15c2106511782955d192 to your computer and use it in GitHub Desktop.
kth element question
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn kth-largest [k coll] | |
(let [reducer (fn [elems elem] | |
(take k (sort > (conj elems elem))))] | |
(last (apply (partial reduce reducer) (split-at k coll))))) | |
(kth-largest 4 (range 100)) | |
;; => returns 96, the 4th-largest element in the range (0, 1, 2, ..., 99) | |
(kth-largest 100 (take 200 (cycle (range 100)))) | |
;; => returns 50, the 100th-largest element in the collection (0, 0, 1, 1, 2, 2, ..., 99, 99) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment