(defn top [n h]
(take n (sort #(- (val %2) (val %1)) h)))
Yup, this code is buggy: it is intended to sort hash entries by descending val order (values are numbers) and it breaks on large data sets.
With large data sets, some values get big and doesn't fit into an int anymore while some stay small thus the difference of such two numbers doesn't fit into an int while Comparator.compare must return an int: overflow.
Here is one way to fix that:
(defn top [n h]
(take n (sort #(.compare clojure.lang.Numbers (val %2) (val %1)) h)))
(defn top [n h]
(take n (sort #(compare (val %2) (val %1)) h)))
No comments:
Post a Comment