September 27, 2018

Just Juxt #44: Pairwise Disjoint Sets (4clojure #153)

Disjoint sets

Given a set of sets, create a function which returns true if no two of those sets have any elements in common and false otherwise. Such sets are usually called pairwise disjoint or mutually disjoint. Some of the test cases are a bit tricky, so pay a little more attention to them.

(ns live.test
  (:require [cljs.test :refer-macros [deftest is run-tests]]))
  
(defn disjoint [s]
  ((comp (partial apply ==)
        (juxt
          (comp (partial reduce +) (partial map count))
          (comp count (partial apply clojure.set/union)))) s))

(deftest disjoint-test
  (is (= (disjoint #{#{\U} #{\s} #{\e \R \E} #{\P \L} #{\.}})
   true))
  (is (= (disjoint #{#{:a :b :c :d :e}
         #{:a :b :c :d}
         #{:a :b :c}
         #{:a :b}
         #{:a}})
   false))
  (is (= (disjoint #{#{[1 2 3] [4 5]}
         #{[1 2] [3 4 5]}
         #{[1] [2] 3 4 5}
         #{1 2 [3 4] [5]}})
   true))
  (is (= (disjoint #{#{'a 'b}
         #{'c 'd 'e}
         #{'f 'g 'h 'i}
         #{''a ''c ''f}})
   true))
  (is (= (disjoint #{#{'(:x :y :z) '(:x :y) '(:z) '()}
         #{#{:x :y :z} #{:x :y} #{:z} #{}}
         #{'[:x :y :z] [:x :y] [:z] [] {}}})
   false))
  (is (= (disjoint #{#{distinct?}
         #{#(-> %) #(-> %)}
         #{#(-> %) #(-> %) #(-> %)}
         #{#(-> %) #(-> %) #(-> %)}})
   true))
  (is (= (disjoint #{#{(#(-> *)) + (quote mapcat) #_ nil}
         #{'+ '* mapcat (comment mapcat)}
         #{(do) set contains? nil?}
         #{, , , #_, , empty?}})
   false)))
  
(run-tests)
Tags: coding exercises KLIPSE 4clojure Cryogen juxt