Solutions to 4Clojure Easy Problems
Mar 29, 2016 · 22 minute read clojureinteractiveFollowing the first post on solutions to 4Clojure problems, in this post I will continue with the next set of problems. Once again all solutions are on GitHub, and if you have any suggestions/alternative solutions I would love to hear from you.
19. Last Element
Write a function which returns the last element in a sequence.
(defn lastelement [s]
(nth s (dec (count s))))
[(= (lastelement [1 2 3 4 5]) 5)
(= (lastelement '(5 4 3)) 3)
(= (lastelement ["b" "c" "d"]) "d")]
20. Penultimate Element
Write a function which returns the second to last element from a sequence.
(defn penultimateelement [s]
(nth s ( (count s) 2)))
[(= (penultimateelement (list 1 2 3 4 5)) 4)
(= (penultimateelement ["a" "b" "c"]) "b")
(= (penultimateelement [[1 2] [3 4]]) [1 2])]
21. Nth Element
Write a function which returns the Nth element from a sequence.
(defn nthelement [s n]
(last (take (inc n) s)))
[(= (nthelement '(4 5 6 7) 2) 6)
(= (nthelement [:a :b :c] 0) :a)
(= (nthelement [1 2 3 4] 1) 2)
(= (nthelement '([1 2] [3 4] [5 6]) 2) [5 6])]
22. Count a Sequence
Write a function which returns the total number of elements in a sequence.
(defn countasequence [s]
(reduce (fn [c _] (inc c)) 0 s))
[(= (countasequence '(1 2 3 3 1)) 5)
(= (countasequence "Hello World") 11)
(= (countasequence [[1 2] [3 4] [5 6]]) 3)
(= (countasequence '(13)) 1)
(= (countasequence '(:a :b :c)) 3)]
23. Reverse a Sequence
Write a function which reverses a sequence.
(defn reverseasequence [s]
(reduce #(cons %2 %1) '() s))
[(= (reverseasequence [1 2 3 4 5]) [5 4 3 2 1])
(= (reverseasequence (sortedset 5 7 2 7)) '(7 5 2))
(= (reverseasequence [[1 2][3 4][5 6]]) [[5 6][3 4][1 2]])]
24. Sum It All Up
Write a function which returns the sum of a sequence of numbers.
(defn sumitallup [s]
(reduce + s))
[(= (sumitallup [1 2 3]) 6)
(= (sumitallup (list 0 2 5 5)) 8)
(= (sumitallup #{4 2 1}) 7)
(= (sumitallup '(0 0 1)) 1)
(= (sumitallup '(1 10 3)) 14)]
25. Find the odd numbers
Write a function which returns only the odd numbers from a sequence.
(defn findtheoddnumbers [s]
(filter odd? s))
[(= (findtheoddnumbers #{1 2 3 4 5}) '(1 3 5))
(= (findtheoddnumbers [4 2 1 6]) '(1))
(= (findtheoddnumbers [2 2 4 6]) '())
(= (findtheoddnumbers [1 1 1 3]) '(1 1 1 3))]
26. Fibonacci Sequence
Write a function which returns the first X fibonacci numbers.
(defn fibonaccisequence [n]
(letfn [(fib [a b] (lazyseq (cons b (fib b (+ a b)))))]
(take n (fib 0 1))))
[(= (fibonaccisequence 3) '(1 1 2))
(= (fibonaccisequence 6) '(1 1 2 3 5 8))
(= (fibonaccisequence 8) '(1 1 2 3 5 8 13 21))]
27. Palindrome Detector
Write a function which returns true
if the given sequence is a palindrome. Hint: "racecar" does not equal '(\r \a \c \e \c \a \r)
(defn palindromedetector [s]
(= (seq s) (reverse s)))
[(false? (palindromedetector '(1 2 3 4 5)))
(true? (palindromedetector "racecar"))
(true? (palindromedetector [:foo :bar :foo]))
(true? (palindromedetector '(1 1 3 3 1 1)))
(false? (palindromedetector '(:a :b :c)))]
28. Flatten a Sequence
Write a function which flattens a sequence.
(defn flattenasequence [s]
(reduce (fn myflatten [collection element]
(if (sequential? element)
(reduce myflatten collection element)
(conj collection element))) [] s))
[(= (flattenasequence '((1 2) 3 [4 [5 6]])) '(1 2 3 4 5 6))
(= (flattenasequence ["a" ["b"] "c"]) '("a" "b" "c"))
(= (flattenasequence '((((:a))))) '(:a))]
29. Get the Caps
Write a function which takes a string and returns a new string containing only the capital letters.
(defn getthecaps [s]
(apply str (reseq #"[AZ]+" s)))
[(= (getthecaps "HeLlO, WoRlD!") "HLOWRD")
(empty? (getthecaps "nothing"))
(= (getthecaps "$#A(*&987Zf") "AZ")]
30. Compress a Sequence
Write a function which removes consecutive duplicates from a sequence.
(defn compressasequence [s]
(map #(first %) (partitionby identity s)))
[(= (apply str (compressasequence "Leeeeeerrroyyy")) "Leroy")
(= (compressasequence [1 1 2 3 3 2 2 3]) '(1 2 3 2 3))
(= (compressasequence [[1 2] [1 2] [3 4] [1 2]]) '([1 2] [3 4] [1 2]))]
31. Pack a Sequence
Write a function which packs consecutive duplicates into sublists.
(defn packasequence [s]
(partitionby identity s))
[(= (packasequence [1 1 2 1 1 1 3 3]) '((1 1) (2) (1 1 1) (3 3)))
(= (packasequence [:a :a :b :b :c]) '((:a :a) (:b :b) (:c)))
(= (packasequence [[1 2] [1 2] [3 4]]) '(([1 2] [1 2]) ([3 4])))]
32. Duplicate a Sequence
Write a function which duplicates each element of a sequence.
(defn duplicateasequence [s]
(reduce #(conj (conj %1 %2) %2) [] s))
[(= (duplicateasequence [1 2 3]) '(1 1 2 2 3 3))
(= (duplicateasequence [:a :a :b :b]) '(:a :a :a :a :b :b :b :b))
(= (duplicateasequence [[1 2] [3 4]]) '([1 2] [1 2] [3 4] [3 4]))
(= (duplicateasequence [[1 2] [3 4]]) '([1 2] [1 2] [3 4] [3 4]))]
33. Replicate a Sequence
Write a function which replicates each element of a sequence a variable number of times.
(defn replicateasequence [s n]
(apply concat (map #(repeat n %) s)))
[(= (replicateasequence [1 2 3] 2) '(1 1 2 2 3 3))
(= (replicateasequence [:a :b] 4) '(:a :a :a :a :b :b :b :b))
(= (replicateasequence [4 5 6] 1) '(4 5 6))
(= (replicateasequence [[1 2] [3 4]] 2) '([1 2] [1 2] [3 4] [3 4]))
(= (replicateasequence [44 33] 2) [44 44 33 33])]
34. Implement range
Write a function which creates a list of all integers in a given range.
(defn implementrange [start end]
(take ( end start) (iterate inc start)))
[(= (implementrange 1 4) '(1 2 3))
(= (implementrange 2 2) '(2 1 0 1))
(= (implementrange 5 8) '(5 6 7))]
38. Maximum value
Write a function which takes a variable number of parameters and returns the maximum value.
(defn maximumvalue [& params]
(reduce
(fn [x y]
(if (< x y) y x))
params))
[(= (maximumvalue 1 8 3 4) 8)
(= (maximumvalue 30 20) 30)
(= (maximumvalue 45 67 11) 67)]
39. Interleave Two Seqs
Write a function which takes two sequences and returns the first item from each, then the second item from each, then the third, etc.
(defn interleavetwoseqs [a b]
(if (<= (count a) (count b))
(flatten (mapindexed (fn [index item] [item (nth b index)]) a))
(flatten (mapindexed (fn [index item] [item (nth b index)]) (take (count b) a)))))
[(= (interleavetwoseqs [1 2 3] [:a :b :c]) '(1 :a 2 :b 3 :c))
(= (interleavetwoseqs [1 2] [3 4 5 6]) '(1 3 2 4))
(= (interleavetwoseqs [1 2 3 4] [5]) [1 5])
(= (interleavetwoseqs [30 20] [25 15]) [30 25 20 15])]
40. Interpose a Seq
Write a function which separates the items of a sequence by an arbitrary value.
(defn interposeaseq [v s]
(rest (mapcat #(list v %) s)))
[(= (interposeaseq 0 [1 2 3]) [1 0 2 0 3])
(= (apply str (interposeaseq ", " ["one" "two" "three"])) "one, two, three")
(= (interposeaseq :z [:a :b :c :d]) [:a :z :b :z :c :z :d])]
41. Drop Every Nth Item
Write a function which drops every Nth item from a sequence.
(defn dropeverynthitem [s n]
(keepindexed #(if (not= (mod %1 n) (dec n)) %2) s))
[(= (dropeverynthitem [1 2 3 4 5 6 7 8] 3) [1 2 4 5 7 8])
(= (dropeverynthitem [:a :b :c :d :e :f] 2) [:a :c :e])
(= (dropeverynthitem [1 2 3 4 5 6] 4) [1 2 3 5 6])]
42. Factorial Fun
Write a function which calculates factorials.
(defn factorialfun [n]
(reduce * (range 1 (+ n 1))))
[(= (factorialfun 1) 1)
(= (factorialfun 3) 6)
(= (factorialfun 5) 120)
(= (factorialfun 8) 40320)]
45. Intro to Iterate
The iterate function can be used to produce an infinite lazy sequence.
(def introtoiterate [1 4 7 10 13])
[(= introtoiterate (take 5 (iterate #(+ 3 %) 1)))]
47. Contain Yourself
The contains?
function checks if a KEY is present in a given collection. This often leads beginner clojurians to use it incorrectly with numerically indexed collections like vectors and lists.
(def containyourself 4)
[(contains? #{4 5 6} containyourself)
(contains? [1 1 1 1 1] containyourself)
(contains? {4 :a 2 :b} containyourself)
(not (contains? [1 2 4] containyourself))]
48. Intro to some
The some function takes a predicate function and a collection. It returns the first logical true value of (predicate x) where x is an item in the collection.
(def introtosome 6)
[(= introtosome (some #{2 7 6} [5 6 7 8]))
(= introtosome (some #(when (even? %) %) [5 6 7 8]))]
49. Split a sequence
Write a function which will split a sequence into two parts. Do not use splitat
.
(defn splitasequence [n s]
(list (take n s) (drop n s)))
[(= (splitasequence 3 [1 2 3 4 5 6]) [[1 2 3] [4 5 6]])
(= (splitasequence 1 [:a :b :c :d]) [[:a] [:b :c :d]])
(= (splitasequence 2 [[1 2] [3 4] [5 6]]) [[[1 2] [3 4]] [[5 6]]])]
51. Advanced Destructuring
Here is an example of some more sophisticated destructuring.
(def advanceddestructuring [1 2 3 4 5])
[(= [1 2 [3 4 5] [1 2 3 4 5]] (let [[a b & c :as d] advanceddestructuring] [a b c d]))]
61. Map Construction
Write a function which takes a vector of keys and a vector of values and constructs a map from them.
(defn mapconstruction [keys values]
(apply assoc {} (interleave keys values)))
[(= (mapconstruction [:a :b :c] [1 2 3]) {:a 1, :b 2, :c 3})
(= (mapconstruction [1 2 3 4] ["one" "two" "three"]) {1 "one", 2 "two", 3 "three"})
(= (mapconstruction [:foo :bar] ["foo" "bar" "baz"]) {:foo "foo", :bar "bar"})]
62. Reimplement Iterate
Given a sideeffect free function f and an initial value x write a function which returns an infinite lazy sequence of x, (f x), (f (f x)), (f (f (f x))), etc.
(defn reimplementiterate [f x]
(cons x (lazyseq (reimplementiterate f (f x)))))
[(= (take 5 (reimplementiterate #(* 2 %) 1)) [1 2 4 8 16])
(= (take 100 (reimplementiterate inc 0)) (take 100 (range)))
(= (take 9 (reimplementiterate #(inc (mod % 3)) 1)) (take 9 (cycle [1 2 3])))]
63. Group a Sequence
Given a function f and a sequence s, write a function which returns a map. The keys should be the values of f applied to each item in s. The value at each key should be a vector of corresponding items in the order they appear in s.
(defn groupasequence [f vals]
(into {}
(map #(vector (f (first %)) (vec %))
(partitionby f (sort vals)))))
[(= (groupasequence #(> % 5) [1 3 6 8]) {false [1 3], true [6 8]})
(= (groupasequence #(apply / %) [[1 2] [2 4] [4 6] [3 6]])
{1/2 [[1 2] [2 4] [3 6]], 2/3 [[4 6]]})
(= (groupasequence count [[1] [1 2] [3] [1 2 3] [2 3]])
{1 [[1] [3]], 2 [[1 2] [2 3]], 3 [[1 2 3]]})]
66. Greatest Common Divisor
Given two integers, write a function which returns the greatest common divisor.
(defn greatestcommondivisor [a b]
(if (= b 0)
a
(recur b (mod a b))))
[(= (greatestcommondivisor 2 4) 2)
(= (greatestcommondivisor 10 5) 5)
(= (greatestcommondivisor 5 7) 1)
(= (greatestcommondivisor 1023 858) 33)]
81. Set Intersection
Write a function which returns the intersection of two sets. The intersection is the subset of items that each set has in common.
(defn setintersection [a b]
(set (filter a b)))
[(= (setintersection #{0 1 2 3} #{2 3 4 5}) #{2 3})
(= (setintersection #{0 1 2} #{3 4 5}) #{})
(= (setintersection #{:a :b :c :d} #{:c :e :a :f :d}) #{:a :c :d})]
83. A HalfTruth
Write a function which takes a variable number of booleans. Your function should return true if some of the parameters are true, but not all of the parameters are true. Otherwise your function should return false.
(defn ahalftruth [& booleans]
(= (set booleans) #{true false}))
[(= false (ahalftruth false false))
(= true (ahalftruth true false))
(= false (ahalftruth true))
(= true (ahalftruth false true false))
(= false (ahalftruth true true true))
(= true (ahalftruth true true true false))]
88. Symmetric Difference
Write a function which returns the symmetric difference of two sets. The symmetric difference is the set of items belonging to one but not both of the two sets.
(require 'clojure.set)
(defn symmetricdifference [a b]
(clojure.set/difference
(clojure.set/union a b)
(clojure.set/intersection a b)))
[(= (symmetricdifference #{1 2 3 4 5 6} #{1 3 5 7}) #{2 4 6 7})
(= (symmetricdifference #{:a :b :c} #{}) #{:a :b :c})
(= (symmetricdifference #{} #{4 5 6}) #{4 5 6})
(= (symmetricdifference #{[1 2] [2 3]} #{[2 3] [3 4]}) #{[1 2] [3 4]})]
90. Cartesian Product
Write a function which calculates the Cartesian product of two sets.
(defn cartesianproduct [a b]
(into #{}
(for [x a y b] (vector x y))))
[(= (cartesianproduct #{"ace" "king" "queen"} #{"♠" "♥" "♦" "♣"})
#{["ace" "♠"] ["ace" "♥"] ["ace" "♦"] ["ace" "♣"]
["king" "♠"] ["king" "♥"] ["king" "♦"] ["king" "♣"]
["queen" "♠"] ["queen" "♥"] ["queen" "♦"] ["queen" "♣"]})
(= (cartesianproduct #{1 2 3} #{4 5})
#{[1 4] [2 4] [3 4] [1 5] [2 5] [3 5]})
(= 300 (count (cartesianproduct (into #{} (range 10))
(into #{} (range 30)))))]
95. To Tree, or not to Tree
Write a predicate which checks whether or not a given sequence represents a binary tree. Each node in the tree must have a value, a left child, and a right child.
(defn binary? [s]
(and
(sequential? s)
(= (count s) 3)
(let [ left (second s)
right (last s)]
(and
(or
(nil? left)
(binary? left))
(or
(nil? right)
(binary? right))))))
[(= (binary? '(:a (:b nil nil) nil))
true)
(= (binary? '(:a (:b nil nil)))
false)
(= (binary? [1 nil [2 [3 nil nil] [4 nil nil]]])
true)
(= (binary? [1 [2 nil nil] [3 nil nil] [4 nil nil]])
false)
(= (binary? [1 [2 [3 [4 nil nil] nil] nil] nil])
true)
(= (binary? [1 [2 [3 [4 false nil] nil] nil] nil])
false)
(= (binary? '(:a nil ()))
false)]
96. Beauty is Symmetry
Let us define a binary tree as "symmetric" if the left half of the tree is the mirror image of the right half of the tree. Write a predicate to determine whether or not a given binary tree is symmetric. (see To Tree, or not to Tree for a reminder on the tree representation we’re using).
(defn beautyissymmetry [s]
{:pre [(sequential? s)
(= (count s) 3)]}
(let [left (second s)
right (last s)
mirror (fn mirror [s] {:pre [(= (count s) 3)]}
(let [left (second s)
right (last s)]
(if (and (nil? left) (nil? right))
s
(list
(first s)
(if (sequential? right) (mirror right) right)
(if (sequential? left) (mirror left) left)))))]
(=
left
(if (sequential? right)
(mirror right)
right))))
[(= (beautyissymmetry '(:a (:b nil nil) (:b nil nil))) true)
(= (beautyissymmetry '(:a (:b nil nil) nil)) false)
(= (beautyissymmetry '(:a (:b nil nil) (:c nil nil))) false)
(= (beautyissymmetry [1 [2 nil [3 [4 [5 nil nil] [6 nil nil]] nil]]
[2 [3 nil [4 [6 nil nil] [5 nil nil]]] nil]])
true)
(= (beautyissymmetry [1 [2 nil [3 [4 [5 nil nil] [6 nil nil]] nil]]
[2 [3 nil [4 [5 nil nil] [6 nil nil]]] nil]])
false)
(= (beautyissymmetry [1 [2 nil [3 [4 [5 nil nil] [6 nil nil]] nil]]
[2 [3 nil [4 [6 nil nil] nil]] nil]])
false)]
97. Pascal’s Triangle
Pascal’s triangle is a triangle of numbers computed using the following rules: * The first row is 1. * Each successive row is computed by adding together adjacent numbers in the row above, and adding a 1 to the beginning and end of the row. Write a function which returns the nth row of Pascal’s Triangle.
(defn pascalstriangle [n]
(last
(take n
(iterate
(fn nextrow [previousrow]
(into []
(map (fn [e] (reduce + e))
(partition 2 1
(conj (into [0] previousrow) 0)))))
[1]))))
[(= (pascalstriangle 1) [1])
(= (map pascalstriangle (range 1 6))
[ [1]
[1 1]
[1 2 1]
[1 3 3 1]
[1 4 6 4 1]])
(= (pascalstriangle 11)
[1 10 45 120 210 252 210 120 45 10 1])]
99. Product Digits
Write a function which multiplies two numbers and returns the result as a sequence of its digits.
(defn productdigits [a b]
(map js/parseInt
(str (* a b))))
[(= (productdigits 1 1) [1])
(= (productdigits 99 9) [8 9 1])
(= (productdigits 999 99) [9 8 9 0 1])]
100. Least Common Multiple
Write a function which calculates the least common multiple. Your function should accept a variable number of positive integers or ratios.
(defn leastcommonmultiple [& n]
(letfn [(gcd [a b]
(if (= b 0)
a
(recur b (mod a b))))
(lcm [a b]
(/ (* a b) (gcd a b)))]
(reduce lcm n)))
[(== (leastcommonmultiple 2 3) 6)
(== (leastcommonmultiple 5 3 7) 105)]
107. Simple closures
Lexical scope and firstclass functions are two of the most basic building blocks of a functional language like Clojure. When you combine the two together, you get something very powerful called lexical closures. With these, you can exercise a great deal of control over the lifetime of your local bindings, saving their values for use later, long after the code you’re running now has finished. It can be hard to follow in the abstract, so let’s build a simple closure. Given a positive integer n, return a function (f x) which computes xn. Observe that the effect of this is to preserve the value of n for use outside the scope in which it is defined.
(defn simpleclosures [n]
(fn exp [x]
(long (Math/pow x n))))
[(= 256 ((simpleclosures 2) 16),
((simpleclosures 8) 2))
(= [1 8 27 64] (map (simpleclosures 3) [1 2 3 4]))
(= [1 2 4 8 16] (map #((simpleclosures %) 2) [0 1 2 3 4]))]
118. Reimplement Map
Map is one of the core elements of a functional programming language. Given a function f and an input sequence s, return a lazy sequence of (f x) for each element x in s.
(defn reimplementmap [f c]
(if (not (empty? c))
(lazyseq
(cons (f (first c))
(reimplementmap f (rest c))))))
[(= [3 4 5 6 7]
(reimplementmap inc [2 3 4 5 6]))
(= (repeat 10 nil)
(reimplementmap (fn [_] nil) (range 10)))
(= [1000000 1000001]
(>> (reimplementmap inc (range))
(drop (dec 1000000))
(take 2)))]
120. Sum of square of digits
Write a function which takes a collection of integers as an argument. Return the count of how many elements are smaller than the sum of their squared component digits. For example: 10 is larger than 1 squared plus 0 squared; whereas 15 is smaller than 1 squared plus 5 squared.
(defn sumofsquareofdigits [c]
(count
(filter #(< (first %) (second %))
(map (fn [d]
(vector (first d)
(reduce + (map #(* % %) (second d)))))
(map (fn [e]
(vector e (map js/parseInt (str e))))
c)))))
[(= 8 (sumofsquareofdigits (range 10)))
(= 19 (sumofsquareofdigits (range 30)))
(= 50 (sumofsquareofdigits (range 100)))
(= 50 (sumofsquareofdigits (range 1000)))]
122. Read a binary number
Convert a binary number, provided in the form of a string, to its numerical value.
(defn readabinarynumber [s]
(int
(reduce +
(mapindexed #(* %2 (Math/pow 2 %1))
(map js/parseInt
(reverse s))))))
[(= 0 (readabinarynumber "0"))
(= 7 (readabinarynumber "111"))
(= 8 (readabinarynumber "1000"))
(= 9 (readabinarynumber "1001"))
(= 255 (readabinarynumber "11111111"))
(= 1365 (readabinarynumber "10101010101"))
(= 65535 (readabinarynumber "1111111111111111"))]
128. Recognize Playing Cards
A standard American deck of playing cards has four suits  spades, hearts, diamonds, and clubs  and thirteen cards in each suit. Two is the lowest rank, followed by other integers up to ten; then the jack, queen, king, and ace. It’s convenient for humans to represent these cards as suit/rank pairs, such as H5 or DQ: the heart five and diamond queen respectively. But these forms are not convenient for programmers, so to write a card game you need some way to parse an input string into meaningful components. For purposes of determining rank, we will define the cards to be valued from 0 (the two) to 12 (the ace). Write a function which converts (for example) the string "SJ" into a map of {:suit :spade, :rank 9}. A ten will always be represented with the single character "T", rather than the two characters "10".
(defn recognizeplayingcards [s]
{:suit ({\S :spades \D :diamond \H :heart \C :club}
(first s))
:rank ({\2 0 \3 1 \4 2 \5 3 \6 4 \7 5 \8 6 \9 7 \T 8 \J 9 \Q 10 \K 11 \A 12}
(second s))})
[(= {:suit :diamond :rank 10} (recognizeplayingcards "DQ"))
(= {:suit :heart :rank 3} (recognizeplayingcards "H5"))
(= {:suit :club :rank 12} (recognizeplayingcards "CA"))
(= (range 13) (map (comp :rank recognizeplayingcards str)
'[S2 S3 S4 S5 S6 S7
S8 S9 ST SJ SQ SK SA]))]
135. Infix Calculator
Your friend Joe is always whining about Lisps using the prefix notation for math. Show him how you could easily write a function that does math using the infix notation. Is your favorite language that flexible, Joe? Write a function that accepts a variable length mathematical expression consisting of numbers and the operations +, , *, and /. Assume a simple calculator that does not do precedence and instead just calculates left to right.
(defn infixcalculator [a op b & more]
(letfn [(infix [a op b] (op a b))]
(if (zero? (count more))
(infix a op b)
(recur (infix a op b) (first more) (second more) (drop 2 more)))))
[(= 7 (infixcalculator 2 + 5))
(= 42 (infixcalculator 38 + 48  2 / 2))
(= 8 (infixcalculator 10 / 2  1 * 2))
(= 72 (infixcalculator 20 / 2 + 2 + 4 + 8  6  10 * 9))]
143. dot product
Create a function that computes the dot product of two sequences. You may assume that the vectors will have the same length.
(defn dotproduct [a b]
(reduce + (map * a b)))
[(= 0 (dotproduct [0 1 0] [1 0 0]))
(= 3 (dotproduct [1 1 1] [1 1 1]))
(= 32 (dotproduct [1 2 3] [4 5 6]))
(= 256 (dotproduct [2 5 6] [100 10 1]))]
146. Trees into tables
Because Clojure’s for macro allows you to "walk" over multiple sequences in a nested fashion, it is excellent for transforming all sorts of sequences. If you don’t want a sequence as your final output (say you want a map), you are often still bestoff using for, because you can produce a sequence and feed it into a map, for example. For this problem, your goal is to "flatten" a map of hashmaps. Each key in your output map should be the "path" that you would have to take in the original map to get to a value, so for example {1 {2 3}} should result in {[1 2] 3}. You only need to flatten one level of maps: if one of the values is a map, just leave it alone. That is, (getin original [k1 k2]) should be the same as (get result [k1 k2])
(defn treesintotables [m]
(into {}
(apply concat
(for [[k v] m]
(map #(vector [k (first %)] (second %)) v)))))
[(= (treesintotables '{a {p 1, q 2}
b {m 3, n 4}})
'{[a p] 1, [a q] 2
[b m] 3, [b n] 4})
(= (treesintotables '{[1] {a b c d}
[2] {q r s t u v w x}})
'{[[1] a] b, [[1] c] d,
[[2] q] r, [[2] s] t,
[[2] u] v, [[2] w] x})
(= (treesintotables '{m {1 [a b c] 3 nil}})
'{[m 1] [a b c], [m 3] nil})]
147. Pascal’s Trapezoid
Write a function that, for any given input vector of numbers, returns an infinite lazy sequence of vectors, where each next one is constructed from the previous following the rules used in Pascal’s Triangle. For example, for [3 1 2], the next row is [3 4 3 2]. Beware of arithmetic overflow! In clojure (since version 1.3 in 2011), if you use an arithmetic operator like + and the result is too large to fit into a 64bit integer, an exception is thrown. You can use +' to indicate that you would rather overflow into Clojure’s slower, arbitraryprecision bigint.
(defn pascalstrapezoid [row]
(iterate
(fn nextrow [previousrow]
(into []
(map (fn [e] (reduce + e))
(partition 2 1
(conj (into [0] previousrow) 0)))))
row))
[(= (second (pascalstrapezoid [2 3 2])) [2 5 5 2])
(= (take 5 (pascalstrapezoid [1])) [[1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]])
(= (take 2 (pascalstrapezoid [3 1 2])) [[3 1 2] [3 4 3 2]])
(= (take 100 (pascalstrapezoid [2 4 2])) (rest (take 101 (pascalstrapezoid [2 2]))))]
153. Pairwise Disjoint Sets
Given a set of sets, create a function which returns true if no two of those sets have any elements in common and false otherwise. Some of the test cases are a bit tricky, so pay a little more attention to them. Such sets are usually called pairwise disjoint or mutually disjoint.
(defn pairwisedisjointsets [s]
(=
(count
(apply concat '() s))
(count
(apply clojure.set/union s))))
[(= (pairwisedisjointsets #{#{\U} #{\s} #{\e \R \E} #{\P \L} #{\.}})
true)
(= (pairwisedisjointsets #{#{:a :b :c :d :e}
#{:a :b :c :d}
#{:a :b :c}
#{:a :b}
#{:a}})
false)
(= (pairwisedisjointsets #{#{[1 2 3] [4 5]}
#{[1 2] [3 4 5]}
#{[1] [2] 3 4 5}
#{1 2 [3 4] [5]}})
true)
(= (pairwisedisjointsets #{#{'a 'b}
#{'c 'd 'e}
#{'f 'g 'h 'i}
#{''a ''c ''f}})
true)
(= (pairwisedisjointsets #{#{'(:x :y :z) '(:x :y) '(:z) '()}
#{#{:x :y :z} #{:x :y} #{:z} #{}}
#{'[:x :y :z] [:x :y] [:z] [] {}}})
false)
(= (pairwisedisjointsets #{#{(= "true") false}
#{:yes :no}
#{(symbol "true") 'false}
#{(keyword "yes") ::no}})
false)
(= (pairwisedisjointsets #{#{distinct?}
#{#(> %) #(> %)}
#{#(> %) #(> %) #(> %)}
#{#(> %) #(> %) #(> %)}})
true)
(= (pairwisedisjointsets #{#{(#(> *)) + (quote mapcat) #_ nil}
#{'+ '* mapcat (comment mapcat)}
#{(do) set contains? nil?}
#{, , , #_, , empty?}})
false)]
157. Indexing Sequences
Transform a sequence into a sequence of pairs containing the original elements along with their index.
(defn indexingsequences [s]
(mapindexed (fn [index element] [element index]) s))
[(= (indexingsequences [:a :b :c]) [[:a 0] [:b 1] [:c 2]])
(= (indexingsequences [0 1 3]) '((0 0) (1 1) (3 2)))
(= (indexingsequences [[:foo] {:bar :baz}]) [[[:foo] 0] [{:bar :baz} 1]])]
166. Comparisons
For any orderable data type it’s possible to derive all of the basic comparison operations (<, ≤, =, ≠, ≥, and >) from a single operation (any operator but = or ≠ will work). Write a function that takes three arguments, a less than operator for the data and two items to compare. The function should return a keyword describing the relationship between the two items. The keywords for the relationship between x and y are as follows:

x = y → :eq

x > y → :gt

x < y → :lt
(defn comparisons [f l r]
(cond
(= (f l r) (f r l)) :eq
(f l r) :lt
:else :gt))
[(= :gt (comparisons < 5 1))
(= :eq (comparisons (fn [x y] (< (count x) (count y))) "pear" "plum"))
(= :lt (comparisons (fn [x y] (< (mod x 5) (mod y 5))) 21 3))
(= :gt (comparisons > 0 2))]
173. Intro to Destructuring 2
Sequential destructuring allows you to bind symbols to parts of sequential things (vectors, lists, seqs, etc.): (let [bindings* ] exprs*) Complete the bindings so all letparts evaluate to 3.
[(= 3
(let [[f x] [+ (range 3)]] (apply f x))
(let [[[f x] b] [[+ 1] 2]] (f x b))
(let [[f x] [inc 2]] (f x)))]