Skip to content

Commit

Permalink
Add q84
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkun committed Oct 25, 2024
1 parent d75fc28 commit 7bd383f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/ex/q084.clj
Original file line number Diff line number Diff line change
@@ -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))))
16 changes: 16 additions & 0 deletions test/ex/q084_test.clj
Original file line number Diff line number Diff line change
@@ -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"]})))))

0 comments on commit 7bd383f

Please sign in to comment.