Skip to content

Instantly share code, notes, and snippets.

View samboozle's full-sized avatar

Samuel Bates samboozle

View GitHub Profile
@samboozle
samboozle / kth-element.clj
Created September 15, 2021 04:42
kth element question
(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)