diff --git a/src/ex/q084.clj b/src/ex/q084.clj new file mode 100644 index 0000000..59046ee --- /dev/null +++ b/src/ex/q084.clj @@ -0,0 +1,20 @@ +;; https://4clojure.oxal.org/#/problem/084 + +(ns ex.q084) + +(defn link? [a b] (= (second a) (first b))) +(defn link [a b] [(first a) (second b)]) +(defn links + [coll] + (loop [start (first coll) tail (rest coll) conns (set coll)] + (if (nil? start) + conns + (recur (first tail) (rest tail) (into conns (map #(link start %) (filter #(link? start %) coll))))))) + +(defn ans + "Problem 84, Transitive Closure" + [coll] + (loop [accum coll conns nil] + (if (= accum conns) + conns + (recur (links accum) accum)))) \ No newline at end of file diff --git a/test/ex/q084_test.clj b/test/ex/q084_test.clj new file mode 100644 index 0000000..d37f51c --- /dev/null +++ b/test/ex/q084_test.clj @@ -0,0 +1,16 @@ +;; https://4clojure.oxal.org/#/problem/084 + +(ns ex.q084-test + (:require [clojure.test :as t] + [ex.q084 :as sut])) + +(t/deftest test-q84 + (t/testing "Problem 84, Transitive Closure" + (t/is (= #{[4 2] [8 4] [8 2] [9 3] [27 9] [27 3]} + (sut/ans #{[8 4] [9 3] [4 2] [27 9]}))) + (t/is (= #{["cat" "man"] ["cat" "snake"] ["man" "snake"] + ["spider" "cat"] ["spider" "man"] ["spider" "snake"]} + (sut/ans #{["cat" "man"] ["man" "snake"] ["spider" "cat"]}))) + (t/is (= #{["father" "son"] ["father" "grandson"] + ["uncle" "cousin"] ["son" "grandson"]} + (sut/ans #{["father" "son"] ["uncle" "cousin"] ["son" "grandson"]}))))) \ No newline at end of file