diff options
| author | Tyler Wardhaugh <tyler.wardhaugh@gmail.com> | 2022-02-19 11:13:41 -0800 |
|---|---|---|
| committer | Tyler Wardhaugh <tyler.wardhaugh@gmail.com> | 2022-02-19 11:13:41 -0800 |
| commit | 891bec3c30670850babb0b8ab8a7d5c6a28bc26c (patch) | |
| tree | 8cd198b49160da5274545e7877dc11d2dd8bde34 | |
| parent | 1e9fe2ad09ce80bdcded14c3c7906bd713bf120f (diff) | |
| download | perlweeklychallenge-club-891bec3c30670850babb0b8ab8a7d5c6a28bc26c.tar.gz perlweeklychallenge-club-891bec3c30670850babb0b8ab8a7d5c6a28bc26c.tar.bz2 perlweeklychallenge-club-891bec3c30670850babb0b8ab8a7d5c6a28bc26c.zip | |
Ch152 (Clojure): Task 2
| -rw-r--r-- | challenge-152/tyler-wardhaugh/clojure/src/c152/t2.clj | 34 | ||||
| -rw-r--r-- | challenge-152/tyler-wardhaugh/clojure/test/c152/t2_test.clj | 5 |
2 files changed, 36 insertions, 3 deletions
diff --git a/challenge-152/tyler-wardhaugh/clojure/src/c152/t2.clj b/challenge-152/tyler-wardhaugh/clojure/src/c152/t2.clj index b659b479a8..cf4dbf27e3 100644 --- a/challenge-152/tyler-wardhaugh/clojure/src/c152/t2.clj +++ b/challenge-152/tyler-wardhaugh/clojure/src/c152/t2.clj @@ -1 +1,33 @@ -(ns c150.t2) +(ns c152.t2 + (:require [clojure.edn :as edn])) + +(def DEFAULT-INPUT ['[(-1,0), (2,2)] '[(0,-1), (4,4)]]) +(def ZERO-RECT [[0 0] [0 0]]) + +(defn rectangle-area + [r] + (let [[[x1 y1] [x2 y2]] r] + (* (abs (- x1 x2)) + (abs (- y1 y2))))) + +(defn overlap + [rs] + (let [firsts (map first rs) + seconds (map second rs) + bottom-left (map (partial apply max) (apply map vector firsts)) + top-right (map (partial apply min) (apply map vector seconds)) + diff (apply min (map - top-right bottom-left))] + (if (pos? diff) [bottom-left top-right] ZERO-RECT))) + +(defn total-area + [r1 r2] + (let [both (transduce (map rectangle-area) + 0 [r1 r2]) + intersection (-> [r1 r2] overlap rectangle-area)] + (- both intersection))) + +(defn -main + "Run Task 2 using rectangles R1 & R2, defaulting to the example given in the + task description." + [& args] + (let [[R1 R2] (or (some->> args (map edn/read-string)) DEFAULT-INPUT)] + (println (total-area R1 R2)))) diff --git a/challenge-152/tyler-wardhaugh/clojure/test/c152/t2_test.clj b/challenge-152/tyler-wardhaugh/clojure/test/c152/t2_test.clj index 35749cb1dd..74f0ec3a11 100644 --- a/challenge-152/tyler-wardhaugh/clojure/test/c152/t2_test.clj +++ b/challenge-152/tyler-wardhaugh/clojure/test/c152/t2_test.clj @@ -1,7 +1,8 @@ (ns c152.t2-test (:require [clojure.test :refer [deftest is testing]] - [c152.t2 :refer []])) + [c152.t2 :refer [total-area]])) (deftest examples (testing "Examples from the test description" - )) + (is (= 22 (total-area '[(-1,0), (2,2)] '[(0,-1), (4,4)]))) + (is (= 25 (total-area '[(-3,-1), (1,3)] '[(-1,-3), (2,2)]))))) |
