Given a sequence of elements, I want to find the n most common elements in decreasing order of frequency. So, for example, I would like to pass this unit test:
(fact "can find 2 most common items in a sequence"
(most-frequent-n 2 ["a" "bb" "a" "x" "bb" "ccc" "dddd" "dddd" "bb" "dddd" "bb"])
=>
'("bb" "dddd"))
I am new to Clojure and still trying to grab the standard library. Here is what I came up with:
(defn- sort-by-val [s] (sort-by val s))
(defn- first-elements [pairs] (map
(defn most-frequent-n [n items]
"return the most common n items, e.g.
(most-frequent-n 2 [:a :b :a :d :x :b :c :d :d :b :d :b]) =>
=> (:d :b)"
(take n (->
items ; [:a :b :a :d :x :b :c :d :d :b :d :b]
frequencies ; {:a 2, :b 4, :d 4, :x 1, :c 1}
seq ; ([:a 2] [:b 4] [:d 4] [:x 1] [:c 1])
sort-by-val ; ([:x 1] [:c 1] [:a 2] [:b 4] [:d 4])
reverse ; ([:d 4] [:b 4] [:a 2] [:c 1] [:x 1])
first-elements))) ; (:d :b :a :c :x)
However, this seems like a complex chain of functions to perform a fairly general operation. Is there a more elegant or more idiomatic (or more efficient) way to do this?
source
share