code-reviews

zendevil 2021-05-08T14:53:08.006Z

Challenge: https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup My attempt:

(defn sockMerchant [n ar]
  "Complexity: O(n), (= (count ar) n)
   TOC: ~14 min"
  (reduce + (map (fn [[_ v]] (if (>= v 2) (quot v 2) 0))
       (frequencies ar)))
  #_(->> (map (fn [[k v]] (if (>= v 2) [k (rem v 2)] nil))
          (frequencies ar)) ;; looked up online
     (remove nil?)) ;; looked up online
)

(sockMerchant 7 [10 20 20 10 10 30 50 10 20])

zendevil 2021-05-08T14:53:39.006500Z

Challenge: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup My attempt:

(defn countingValleys [steps path]
  "Complexity: O(n), (= steps n)
   TOC: ~ 28 min"
  (loop [path- (split path #"") dist-from-sea 0 valleys 0] ;; looked up online
    (if (seq path-) ;; looked up online
      (if (= (first path-) "U")
        (recur (rest path-) (inc dist-from-sea)
               (if (= (inc dist-from-sea) 0) (inc valleys) valleys))
        (recur (rest path-) (dec dist-from-sea) valleys))
      valleys)))

(countingValleys 8 "UDDDUDUU")

seancorfield 2021-05-08T17:07:39.007500Z

My first comment would be that camelCase is not idiomatic in Clojure — kebab-case is what folks will expect.

💯 1
seancorfield 2021-05-08T17:14:43.008700Z

(Weird puzzle: sock merchant doesn’t use n at all, but it’s supposed to be the length of the array? And you’re passing 7 instead of 9 in your call)

seancorfield 2021-05-08T17:20:17.010700Z

For the sock merchant, I’d go with something more straightforward that is closer to the problem statement:

user=> (defn sock-merchant [n ar] 
         (reduce (fn [[socks pairs] sock] 
                   (if (contains? socks sock) 
                     [(disj socks sock) (inc pairs)] 
                     [(conj socks sock) pairs])) 
                 [#{} 0] 
                 ar))
That returns a pair: the unmatched socks leftover and the number of pairs matched.

👍 1
seancorfield 2021-05-08T17:27:19.011900Z

In the second function, using - as a suffix on a binding is a bit unusual. Most people would just reuse path (and shadow the parameter) or maybe use path'.

seancorfield 2021-05-08T17:30:42.014100Z

I’d probably use (seq path) instead of (split path #"") and then (if path ..) inside the loop, and recur with (next path)next returns nil on an empty sequence, rest returns an empty sequence. And test against \U at that point since (seq "str") produces (\s \t \r) with characters, not strings.

seancorfield 2021-05-08T17:33:57.014900Z

Otherwise, I’d probably follow the same overall structure as you did @ps for counting-valleys.