Skip to content

Instantly share code, notes, and snippets.

@danielcompton
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielcompton/4b1a59054a40a89c19ec to your computer and use it in GitHub Desktop.
Save danielcompton/4b1a59054a40a89c19ec to your computer and use it in GitHub Desktop.
Sorted frequencies
;; standard frequencies
;; Execution time mean : 196.445451 µs
(defn dna-frequencies [coll]
(->> (frequencies coll)
(sort-by key)
(map val)
(clojure.string/join " ")))
;; sorted map
;; Execution time mean : 185.372507 µs
(defn sorted-frequencies
"Returns a sorted map from distinct items in coll to the number of times
they appear."
[coll]
(reduce (fn [counts x]
(assoc counts x (inc (get counts x 0))))
(sorted-map)
coll))
(defn dna-frequencies2 [coll]
(->> (sorted-frequencies coll)
(map val)
(clojure.string/join " ")))
;; tree map
;; Execution time mean : 37.068014 µs
(defn sorted-frequencies-treemap
[coll]
(reduce (fn [^java.util.TreeMap counts x]
(.put counts x (inc (if (.containsKey counts x)
(.get counts x)
0)))
counts)
(TreeMap.)
coll))
(defn dna-frequencies3 [coll]
(->> (sorted-frequencies-treemap coll)
(map val)
(clojure.string/join " ")))
;; avl
;; Execution time mean : 147.098228 µs
(defn sorted-frequencies-avl [coll]
(persistent!
(reduce (fn [counts x]
(assoc! counts x (inc (get counts x 0))))
(transient (avl/sorted-map)) coll)))
(defn dna-frequencies4 [coll]
(->> (sorted-frequencies-avl coll)
(map val)
(clojure.string/join " ")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment