Skip to content

Latest commit

 

History

History
900 lines (703 loc) · 15.6 KB

README.md

File metadata and controls

900 lines (703 loc) · 15.6 KB

My solutions for 4clojure exercises.

List is not complete yet, because I'm still working on it.

4clojure solutions

Problem 1

Nothing but the Truth

(= 1 1)
Problem 2

Simple Math

4
Problem 3

Intro to Strings

"HELLO WORLD"
Problem 4

Intro to Lists

:a :b :c
Problem 5

Lists: conj

'(1 2 3 4)
Problem 6

Intro to Vectors

:a :b :c
Problem 7

Vectors: conj

[1 2 3 4]
Problem 8

Intro to Sets

#{:a :b :c :d}
Problem 9

Sets: conj

2
Problem 10

Intro to Maps

20
Problem 11

Maps: conj

[:b 2]
Problem 12

Intro to Sequences

3
Problem 13

Sequences: rest

'(20 30 40)
Problem 14

Intro to Functions

8
Problem 15

Double Down

#(* 2 %)
Problem 16

Hello World

#(str "Hello, " % "!")
Problem 17

Sequences: map

'(6 7 8)
Problem 18

Sequences: filter

'(6 7)
Problem 19

Last Element

#(first (reverse %))
Problem 20

Penultimate Element

#(second (reverse %))
Problem 21

Nth Element

#(get (vec %1) %2)
Problem 22

Count a Sequence

#(reduce (fn [acc x]
           (inc acc))
         0 %)
Problem 23

Reverse a Sequence

#(reduce (fn [acc x]
           (cons x acc))
         (empty %)
         %)
Problem 24

Sum It All Up

#(apply + %)
Problem 25

Find the odd numbers

#(reverse (reduce (fn [acc x]
                    (if (odd? x)
                      (conj acc x)
                      acc))
                  '() %))
Problem 26

Fibonacci Sequence

#(loop [x [1 1]]
   (if (= (count x) %)
     x
     (recur (conj x (apply + (take 2 (reverse x)))))))
Problem 27

Palindrome Detector

(if (string? %)
  (= (clojure.string/reverse %) %)
  (= (reverse %) %))
Problem 28

Flatten a Sequence

#(reverse (reduce
           (fn rec-flatten [acc item]
             (if (coll? item) (reduce rec-flatten acc item)
                 (conj acc item)))
           '()
           %))
Problem 29

Get the Caps

#(apply str(filter (set (map char (range 65 91))) %))
Problem 30

Compress a Sequence

#(map first (partition-by identity %))
Problem 31

Pack a Sequence

#(partition-by identity %)
Problem 32

Duplicate a Sequence

#(seq (reduce (fn [acc item]
                (-> acc
                    (conj item)
                    (conj item)))
              [] %))
Problem 33

Replicate a Sequence

#(mapcat (fn [item]
           (take %2 (repeat item)))
         %1)
Problem 34

Implement range

#(take (- %2 %1) (iterate inc %1))
Problem 35

Local bindings

7
Problem 36

Let it Be

[x 7 y 3 z 1]
Problem 37

Regular Expressions

"ABC"
Problem 38

Maximum value

(fn [& args]
  (last (sort args)))
Problem 39

Interleave Two Seqs

#(flatten (map (fn [f s]
                 (conj '() s f))
               %1 %2))
Problem 40

Interpose a Seq

#(take (- (* 2 (count %2)) 1)
       (interleave %2 (repeat %1)))
Problem 41

Drop Every Nth Item

#(mapcat (fn [a]
           (take (- %2 1) a))
         (partition-all %2 %1))
Problem 42

Factorial Fun

#(apply * (range 1 (+ 1 %)))
Problem 43

Reverse Interleave

#(apply map (fn [& args]
              args)
        (partition %2 %1))
Problem 44

Rotate Sequence

#(let [new-coll (if (pos? %1)
                  %2
                  (reverse %2))
       new-position (if (pos? %1)
                      %1
                      (+ %1 (* -2 %1)))
       real-position (mod new-position (count %2))
       rotated (flatten
                (reduce
                 (fn [[acc-x acc-y] [x y]]
                   (if (< x real-position)
                     [acc-x (conj acc-y y)]
                     [(conj acc-x y) acc-y]))
                 [[] []]
                 (map-indexed vector new-coll)))]
   (if (pos? %1)
     rotated
     (reverse rotated)))
Problem 45

Intro to Iterate

'(1 4 7 10 13)
Problem 46

Flipping out

#(fn [x y]
   (% y x))
Problem 47

Contain Yourself

4
Problem 48

Intro to some

6
Problem 49

Split a sequence

#(vector (take %1 %2) (drop %1 %2))
Problem 50

Split by Type

#(vals (group-by type %))
Problem 51

Advanced Destructuring

[1 2 3 4 5]
Problem 52

Intro to some

[c e]

Problem 53

Longest Increasing Sub-Seq

(fn [coll]
  (let [longest-seq (->> (reduce (fn [acc item]
                                     (cond
                                         (= (ffirst acc) nil) (conj (rest acc) (conj (first acc) item))
                                         (= (inc (ffirst acc)) item) (conj (rest acc) (conj (first acc) item))
                                         :else (conj acc (list item))))
                                 '(())
                                 coll)
                         (sort-by count)
                         last
                         reverse
                         vec)]
     (if (> (count longest-seq) 1)
       longest-seq
       [])))
Problem 54

Partition a Sequence

(fn [par-num coll]
  (->> (reduce (fn [acc item]
                 (if (= (count (first acc)) par-num)
                   (conj acc (list item))
                   (conj (rest acc) (conj (first acc) item))))
               '(())
               coll)
       (filter #(= par-num (count %)))
       (map reverse)
       reverse))
Problem 55

Count Occurrences

#(into (sorted-map)
       (map (fn [[k v]]
              {k (count v)})
            (group-by identity %)))
Problem 56

Find Distinct Items

(fn [coll]
  (reduce (fn [acc item]
            (if ((set acc) item)
              acc
              (conj acc item)))
          []
          coll))

Problem 57

Simple Recursion

'(5 4 3 2 1)
Problem 58

Function Composition

(fn my-comp [& fns]
  (fn [& args]
    (if (= (count fns) 1)
      (apply (first fns) args)
      ((apply my-comp (butlast fns))
       (apply (last fns) args)))))
Problem 59

Juxtaposition

(fn [& fns]
  (fn [& args]
    (reduce #(conj %1 (apply %2 args)) [] fns)))
Problem 60
	(fn problem60
  ([f coll]
   (problem60 f (first coll) (rest coll)))
  ([f init coll]
   (if (seq coll)
     (cons init (lazy-seq (problem60 f (f init (first coll)) (rest coll))))
     (list init))))
Problem 61

Map Construction

#(apply merge (map (fn [k v]
                     {k v})
                   %1
                   %2))
Problem 62

Re-implement Iterate

(fn my-iterate [fnc x]
  (cons x (lazy-seq (my-iterate fnc (fnc x)))))
Problem 63

Group a Sequence

#(apply merge-with concat
        (map (fn [item]
               (hash-map (%1 item) [item]))
             %2))
Problem 64

Intro to reduce

+
Problem 65

Black Box Testing

#(let [empty-coll (empty %)
       coll-with-items (conj empty-coll [1 2] [1 2] [3 4])]
    (if (= (count coll-with-items) 3)
      (if (= (first (conj coll-with-items [5 6])) [5 6])
        :list
        :vector)
      (if (contains? coll-with-items 1)
        :map
        :set))))
Problem 66

Greatest Common Divisor

#(loop [a (max %1 %2)
        b (min %1 %2)
        r (rem a b)]
   (if (= r 0)
     b
     (recur b r (rem b r))))

Problem 67

(fn problem67
  ([count-nr] (problem67 count-nr 3 [2]))
  ([count-nr test-nr coll]
   (if (= (count coll) count-nr)
     coll
     (if (some #(integer? (/ test-nr %)) coll)
         (recur count-nr (inc test-nr) coll)
         (recur count-nr (inc test-nr) (conj coll test-nr))))))
Problem 68

Recurring Theme

[7 6 5 4 3]
Problem 69

Merge with a function

(fn [f & args]
  (into {} (map (fn [[k v]]                                                                                                                                                                                                                                                                                                
                  {k (if (> (count (vals v)) 1)                                                                                                                                                                                                                                                                            
                       (apply f (vals v))                                                                                                                                                                                                                                                                                  
                       (first (vals v)))})                                                                                                                                                                                                                                                                                 
                (->> args                                                                                                                                                                                                                                                                                                  
                     (apply concat)                                                                                                                                                                                                                                                                                        
                     (group-by first)))))
Problem 70

Word Sortinf

(sort-by clojure.string/lower-case (-> s
                                       (clojure.string/replace #"[.!?]" "")
                                       (clojure.string/split #" "))))
Problem 71

Rearranging Code: ->

last
Problem 72

Rearranging Code: ->>

reduce +
Problem 74

Filter Perfect Squares

(fn problem74 [string-of-integers]
  (let [lazy-prime (filter (fn [nr]
                             (not-any? #(zero? (mod nr %))
                                       (range 2 (dec nr)))) (iterate inc 2))]
    (letfn [(prime-factorization
              ([nr] (prime-factorization nr (take-while #(>= nr %) lazy-prime) []))
              ([nr primes prime-factors]
               (let [prime-number (first primes)
                     quotient (/ nr prime-number)]
                 (if (= quotient 1)
                   (conj prime-factors prime-number)
                   (if (integer? quotient)
                     (recur quotient primes (conj prime-factors prime-number))
                     (recur nr (rest primes) prime-factors))))))
            (is-perfect-square? [nr]
              (not-any? (fn [[k v]]
                          (odd? v))
                        (frequencies (prime-factorization nr))))]
      (clojure.string/join ","
                           (filter #(->> %
                                         read-string
                                         is-perfect-square?) 
	                                (clojure.string/split string-of-integers #","))))))
Problem 81

Set Intersection

#(apply sorted-set
        (filter
         (fn [x]
           (contains? %1 x))
         %2))
Problem 83

A Half-Truth

(fn [& args]
  (and (contains? (set args) false)
       (contains? (set args) true)))
Problem 88

Symmetric Difference

#(set (concat (apply disj %1 %2) (apply disj %2 %1)))
Problem 90

Cartesian Product

#(set
  (for [x %1
        y %2]
    [x y]))
Problem 95

To Tree, or not to Tree

(fn tree [coll]
  (let [inner-coll (first (filter coll? coll))
        is-binary (odd? (count (filter #(and (not= % true) (not= % false)) (flatten coll))))]
    (if (and is-binary (= (count inner-coll) 3))
      (tree inner-coll)
      is-binary)))
Problem 97

Pascal's Triangle

(fn pascal [row]
  (map (comp last take)
       (reverse (range 1 (+ 1 row)))
       (take row (iterate (partial reductions +) (take row (repeat 1))))))
Problem 99

Product Digits

#(->> (* %1 %2)
      str
      seq
      (map (comp read-string str)))
Problem 100

Least Common Multiple

(fn [& args]
  (letfn [(gcd [x y]
            (if (= x y)
              x
              (if (< x y)
                (recur x (- y x))
                (recur y (- x y)))))
          (lcm [x y]
            (/ (* x y) (gcd x y)))]
    (reduce lcm args)))
Problem 107

Simple closures

#(fn [y]
   (apply * (repeat % y)))
Problem 118

Re-implement Map

(fn my-map [f s]
  (when (seq s)
    (cons (f (first s))
          (lazy-seq (my-map f (rest s))))))
Problem 120

Sum of square of digits

(fn [seq]
  (-> (fn [item]
        (if (> 10 item)
          (< item (* item item))
          (< item (apply + (map (comp #(* % %) read-string str first)
                                (split-at 1 (str item)))))))
      (filter seq)
      count))
Problem 122

Read a binary number

(fn [s]
  (apply + (map (fn [x]
                  (apply * (repeat x 2)))
                (keep-indexed #(if (= 1 %2) %1)
                              (mapv (comp read-string str) (reverse s))))))
Problem 126

Through the Looking Class

java.lang.Class

Problem 128

Recognize Playing Cards

#(let [cards-suits {"S" :spade
                    "H" :heart
                    "D" :diamond
                    "C" :club}
       cards-rank (zipmap
                   (conj (->> (range 2 10)
                              (map str)
                              (vec))
                         "T" "J" "Q" "K" "A")
                   (range 13))
       card-data (map str (seq %))
       suit (cards-suits (first card-data))
       rank (cards-rank (last card-data))]
   {:suit suit :rank rank})
Problem 134

A nil key

(fn [k m]
  (and (contains? m k)
       (nil? (m k))))
Problem 135

Infix Calculator

(fn infix-calculator [& args]
  (let [[first-operand operator second-operand] (take 3 args)
        result (operator first-operand second-operand)]
    (if (= (count args) 3)
      result
      (apply infix-calculator (cons result (drop 3 args))))))
Problem 143

dot product

#(apply + (map * %1 %2))
Problem 145

For the win

'(1 5 9 13 17 21 25 29 33 37)
Problem 156

Map Defaults

#(zipmap %2 (repeat %1))
Problem 157

Indexing Sequences

#(map-indexed (fn [itm idx]
                [idx itm])%)
Problem 161

Subset and Superset

#{1 2}
Problem 162

Logical falsity and truth

1
Problem 166

Comparisons

#(cond
   (%1 %2 %3) :lt
   (%1 %3 %2) :gt
   :else :eq)