Skip to content

Instantly share code, notes, and snippets.

@Akeboshiwind
Last active July 27, 2018 20:03
Show Gist options
  • Save Akeboshiwind/d3045eb27d6c352c1b809f8b89497c83 to your computer and use it in GitHub Desktop.
Save Akeboshiwind/d3045eb27d6c352c1b809f8b89497c83 to your computer and use it in GitHub Desktop.
Heavy Hitters algorithm
(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))))
@Akeboshiwind
Copy link
Author

Akeboshiwind commented Jul 27, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment