Skip to content

Latest commit

 

History

History
94 lines (71 loc) · 2.74 KB

july-15-2020.md

File metadata and controls

94 lines (71 loc) · 2.74 KB

ClojureFam - Week 4 - Day 3

This post is going to be quite sparse since I was pretty occupied with normal life stuff. I mostly just solved a few 4Clojure problems today to hit a grand total of 90 solved problems. I'm also finally all done with the Easy problems!

4Clojure Problems

Easy

No. 120 Sum of square of digits

(defn sum-of-square
  [xs]
  (let [make-digit (fn [n] (map #(Integer/valueOf (str %)) (String/valueOf n)))
        sqr-digit (fn [n] (apply + (map #(* % %) (make-digit n))))]
    (count (filter #(> (sqr-digit %) %) xs))))

(sum-of-square (range 100))
;; 50

No. 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 common1 and false otherwise. Some of the test cases are a bit tricky, so pay a little more attention to them.

(defn pairwise
  [xs]
  (let [ls (for [x xs y xs :when (not= x y)] [x y])]
    (apply = 0 (map #(count (clojure.set/intersection (first %) (second %))) ls))))

;; (pairwise #{#{'(:x :y :z) '(:x :y) '(:z) '()}
;;           #{#{:x :y :z} #{:x :y} #{:z} #{}}
;;             #{'[:x :y :z] [:x :y] [:z] [] {}}})

No. 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 lcm
  ([x y & args]
   (reduce lcm (conj args y x)))
  ([x y]
   (let [gcd (fn [a b] (if (zero? b) a (recur b (rem a b))))]
     (/ (* x y) (gcd x y)))))

;; (lcm 1/3 2/5)

Medium

No. 54 Partition a Sequence Write a function which returns a sequence of lists of x items each. Lists of less than x items should not be returned.

(defn my-partition
  ([n x] (my-partition n x []))
  ([n x y]
   (let [fpl (take n x)
         spl (drop n x)]
     (if (> n (count spl))
       (conj y fpl)
       (my-partition n spl (conj y fpl))))))

;; (my-partition 3 (range 8))
;; => [(0 1 2) (3 4 5)]

No. 74 Filter Perfect Squares Given a string of comma separated integers, write a function which returns a new comma separated string that only contains the numbers which are perfect squares.

(defn filter-sq
  [s]
  (let [xs (clojure.string/split s #",")
        ms (map #(Integer/valueOf %) xs)]
    (->> ms
         (filter (fn [x]
                   (let [sqra (Math/sqrt x)]
                     (== sqra (int sqra)))))
         (clojure.string/join #","))))

;; (filter-sq "4,5,6,7,8,9")
;; => "4,9"

Takeaways

Some of the Easy problems weren't all that "easy" to solve. I definitely benefited from working on them after a while. When I got started on them today, I was able to figure out solutions to them without much consternation.

Today's tally -

  • 3 Easy problems
  • 2 Medium problems