code-reviews

tdantas 2019-10-07T17:15:38.038300Z

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)))

tdantas 2019-10-07T17:15:51.038600Z

thanks @dominicm and @jaihindhreddy

2019-10-07T17:21:59.039300Z

@oliv another option: sorted-set instead of [], then the sorting is implicit, and it is splittable for binary search

2019-10-07T17:22:31.039700Z

that also removes dupes - may be incompatibel with some other requirement

tdantas 2019-10-07T17:26:03.039900Z

nice @noisesmith, good way to distinct values and sort

jaihindhreddy 2019-10-07T18:20:58.040200Z

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)))

jaihindhreddy 2019-10-07T18:32:46.040400Z

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 😅

tdantas 2019-10-07T20:02:44.041100Z

Thanks for your tips , gonna update my code