Fork me on GitHub
#code-reviews
<
2021-05-08
>
zendevil.eth14:05:08

``````(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.eth14:05:39

``````(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")``````

seancorfield17:05:39

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

💯 3
seancorfield17:05:43

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

seancorfield17:05:17

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.

👍 3
raspasov05:05:13

I like this solution. Occasionally, I fall in the trap of always looking for the “higher level” solution where a more “procedural” solution would be OK.

seancorfield17:05:19

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'`.

seancorfield17:05:42

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.

seancorfield17:05:57

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