This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2019-10-07
Channels
- # aleph (1)
- # announcements (2)
- # babashka (1)
- # beginners (49)
- # calva (1)
- # cider (5)
- # clj-kondo (14)
- # cljdoc (11)
- # cljsrn (6)
- # clojure (120)
- # clojure-austin (1)
- # clojure-europe (6)
- # clojure-finland (3)
- # clojure-italy (29)
- # clojure-nl (6)
- # clojure-spec (38)
- # clojure-uk (14)
- # clojurescript (65)
- # code-reviews (8)
- # cursive (20)
- # data-science (1)
- # datascript (5)
- # datomic (57)
- # emacs (6)
- # figwheel-main (2)
- # fulcro (32)
- # funcool (1)
- # jackdaw (7)
- # jobs (3)
- # joker (7)
- # kaocha (8)
- # keechma (3)
- # nrepl (7)
- # off-topic (25)
- # quil (3)
- # re-frame (10)
- # reagent (43)
- # remote-jobs (1)
- # ring (1)
- # shadow-cljs (173)
- # sim-testing (1)
- # spacemacs (1)
- # sql (3)
- # tools-deps (34)
the sort
is returning an ArraySeq which does not implements RandomAccess interface.
to proper use the binarySearch full power, your datatype must implement the RandomAccess (for instance PersistentVector )
final solution , less than 1 second to run on 100K items
(defn solution [team-a team-b]
(let [steam-a (into [] (sort team-a))
search #(java.util.Collections/binarySearch steam-a %1)
mapper (comp inc search)]
(mapv #(Math/abs (mapper %1)) team-b)))
A style point: the inc
and the Math/abs
can be done inline.
Also, because steam-a
doesn't escape the function, we can make it a mutable array of primitive ints, which has excellent cache locality. Throw in a couple of type hints to remove reflection, and you got a pretty fast solution:
(defn solution [team-a team-b]
(let [steam-a ^ints (into-array Integer/TYPE (sort team-a))]
(mapv #(-> (java.util.Arrays/binarySearch steam-a ^int %)
inc
Math/abs)
team-b)))
In fact, we can do the sort in-place in the array to get even more perf.
(defn solution [team-a team-b]
(let [steam-a ^ints (into-array Integer/TYPE team-a)]
; Sorts the array in-place
(java.util.Arrays/sort steam-a)
(mapv #(-> (java.util.Arrays/binarySearch steam-a ^int %)
inc
Math/abs)
team-b)))
Note though, haven't benchmarked, so perf claims might as well be baloney 😅thanks @dominicm and @jaihindhreddy
@oliv another option: sorted-set
instead of []
, then the sorting is implicit, and it is splittable for binary search
that also removes dupes - may be incompatibel with some other requirement
nice @noisesmith, good way to distinct values and sort