programming kata

1 minute read

Code kata

Problem Write a function steps, that takes a sequence and makes a deeply nested structure from it: (steps [1 2 3 4]) ;=> [1 [2 [3 [4 []]]]] Solution 1 (defn steps [s] (if (seq s) [(first s) (steps (rest s))] [])) Solution 2 Lazy version: (defn lz-steps [s] (lazy-seq (if (seq s) [(first s) (lz-steps (rest s))] []))) Note To see the difference, call the function like this:

1 minute read

Code kata

Problem Suppose a binary tree structure looks like this: {:val value :L <left-node> :R <right-node>} Write a function to balance insert node into the tree. Solution (defn insert [tree x] (cond (nil? tree) {:val x :L nil :R nil} (< x (:val tree)) (assoc tree :L (insert (:L tree) x)) :else (assoc tree :R (insert (:R tree) x)))) Note Here is the function to traverse the tree: (defn traverse [tree] (when tree (concat (traverse (:L tree)) [(:val tree)] (traverse (:R tree))))) Here is a helper function to create a tree.

1 minute read

Code kata

Problem Write a function to determine if a vector contains a set of items. Solution (defn containsv [v & items] (some (set items) v)) Note Using a set as the predicate supplied to some allows you to check whether any of the truthy values in the set are contained within the given sequence. This is a frequently used Clojure idiom for searching for containment within a sequence.

1 minute read

Code kata

Problem Write a function to determine if a number is a triangular number. Solutions Solution 1 (defn nth-triangle [n] (apply + (range (inc n)))) (defn is-triangle-number [n] (loop [i 0] (cond (> n (nth-triangle i)) (recur (inc i)) (= n (nth-triangle i)) true :else false))) Solution 2 (defn is-triangle-number [n] (loop [tri 0 i 1] (cond (> n tri) (recur (+ tri i) (inc i)) (= n tri) true :else false))) Note Solution 1 is the first that came to my mind, but it has a typical problem: redundant calculation.