Skip to content

Instantly share code, notes, and snippets.

@samboozle
Created September 15, 2021 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samboozle/e4f2de4beafd15c2106511782955d192 to your computer and use it in GitHub Desktop.
Save samboozle/e4f2de4beafd15c2106511782955d192 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment