4clojure Notes
(solutions and notes when I worked on 4clojure problems)
Difficulty: Elementary
the most straightforward is using str
:
#(str "Hello, " % "!")
but I found immo's solution:
format "Hello, %s!"
is simple too (not a function as required, but it passes the unit tests :D)
also the solution is simple: reduce +
but apply +
also works.
my solution:
#(apply hash-map (interleave %2 (repeat %1)))
other solutions:
when transforming from one collection type to another, can always use reduce
(austintaylor's solution):
(fn [x s] (reduce #(assoc %1 %2 x) {} s))
and immo's neat solution:
#(zipmap %2 (repeat %))
Difficulty: Easy
my solution: (comp first reverse)
also works: #(first (reverse %))
and #(-> % reverse first)
learned that when there's only one argument passing to each function, use comp
another interesting solution is (comp peek vec)
by immo.
my solution: #(reduce + (map (constantly 1) %))
and cheated solution from immo: #(.size (vec %))
my solution:
(fn [n]
(take n
(map first (iterate (fn [[x y]] [y (+ x y)]) [1 1]))))
the best is _pcl's solution:
;; TDD principle: Write the minimum amount of code required to make the test pass :)
(fn [i] (take i '(1 1 2 3 5 8 13 21)))
my solution:
(fn f [s] (if (sequential? s) (mapcat f s) (list s)))
however, others are using coll?
instead of sequential?
my solution:
(fn [s] (reduce (fn [acc x] (conj acc x x)) [] s))
the best is #(interleave % %)
another one is mapcat #(list % %)
my solution:
(fn [& n] (reduce (fn [x acc] (if (> x acc) x acc)) 0 n))
not good, I know, especially comparing to immo's
#(last (sort %&))