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.

1 minute read

Code kata

Problem Implement take-nth. Solutions Solution 1 (defn my-take-nth [n col] (loop [i 0 result []] (if (= i (count col)) result (if (= 0 (mod i n)) (recur (inc i) (conj result (nth col i))) (recur (inc i) result))))) solution 2 (defn my-take-nth2 [n col] (->> col (map-indexed (fn [i x] [i x])) (filter (fn [[i x]] (= 0 (mod i 2)))) (mapv (fn [[i x]] x))))

1 minute read

Code kata

Problem Trolls are attacking your comment section! A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat. Your task is to write a function that takes a string and return a new string with all vowels removed. For example, the string “This website is for losers LOL!” would become “Ths wbst s fr lsrs LL!”. Solution Solution 1 (defn disemvowel [string] (reduce (fn [result next] (if (#{\A \E \I \O \U \a \e \i \o \u} next) result (str result next))) "" string)) Solution 2 (defn disemvowel [string] (apply str (remove (set "AEIOUaeiou") string)))