4 ms·
I realize that the interviewee was in time pressure, but really should've made smaller helper functions - probably would have helped ease the stress a lot. Poss
by quantumtremor 11y ago
I realize that the interviewee was in time pressure, but really should've made smaller helper functions - probably would have helped ease the stress a lot. Possibly also unfamiliar with Clojure/functional programming as someone mentioned, given that his "happy" function uses loop unnecessarily. Here's my solution.
(defn int-to-digits [n]
(map #(Character/getNumericValue %) (str n)))
(I had to Google Character/getNumericValue - doubt anyone expects you to memorize that).
(defn next-happy [n]
(reduce +
(map #(* % %) (int-to-digits n))))
(defn happy? [n]
(loop [n n seen #{}]
(if (contains? seen n)
(== n 1)
(recur (next-happy n) (conj seen n)))))
A lot simpler to reason about, even if the initial implementation did have bugs.
- dllthomas 11y ago"really should've made smaller helper functions" I couldn't agree more. Especially when you're under pressure, bite off smaller pieces. Not only is it possibly better practice in general, but in a time of diminished cognitive capacity (such as when much of your bandwidth is being eaten up wondering how you're coming off) they will be easier to get right, and small successes will help ease your stress as much as they help solve the problem.