Created
October 22, 2015 14:40
-
-
Save orther/60fecbe93c1c32ce8639 to your computer and use it in GitHub Desktop.
Playing with getting top two numbers w/ O(n)
This file contains hidden or 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
(require '[clojure.core.reducers :as r]) | |
(defn top-two | |
[[big1 big2 :as acc] x] | |
(cond | |
(> x big1) [x big1] | |
(> x big2) [big1 x] | |
:else acc)) | |
(defn top-two+ | |
([] [0 0]) | |
([acc x] (top-two acc x))) | |
(time (def nums (doall (take 1000000 (range))))) | |
(time (second (reduce top-two [0 0] nums))) | |
(time (second (r/reduce top-two+ nums))) | |
(time (second (r/fold top-two+ nums))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on: http://codereview.stackexchange.com/questions/16047/find-largest-two-numbers-from-list-using-clojure