Last active
July 27, 2018 20:03
-
-
Save Akeboshiwind/d3045eb27d6c352c1b809f8b89497c83 to your computer and use it in GitHub Desktop.
Heavy Hitters algorithm
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
(defn heavy-hitter | |
"Output the lement in the list that came up more than 50% of the time, nil otherwise." | |
[lst] | |
(let [heavy (heavy-hitter* lst)] | |
(when (->> lst | |
(filter (partial = heavy)) | |
(count) | |
(<= (/ (count lst) 2))) | |
heavy))) | |
(defn- heavy-hitter* | |
"Output the element in the list that most likely came up most." | |
[lst] | |
(first | |
(reduce | |
(fn [[heavy count] next] | |
(if (= heavy next) | |
[heavy (inc count)] | |
(if (= count 0) | |
[next 1] | |
[heavy (dec count)]))) | |
[(first lst) 1] | |
(rest lst)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An algorithm that finds the element in the list that finds the most common element in a list.
It's good because although it requires two passes of the data, it only has constant space requirements.