August 13, 2018

4clojure 153 - Pairwise Disjoint Sets

Given a set of sets, 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.

1Such sets are usually called pairwise disjoint or mutually disjoint.

(ns live.test
  (:require [cljs.test :refer-macros [deftest is run-tests]]))

(defn disjoint [s]
  (= (count (set (reduce concat s)))
     (reduce + (map count 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 #{#{(= "true") false}
         #{:yes :no}
         #{(class 1) 0}
         #{(symbol "true") 'false}
         #{(keyword "yes") ::no}
         #{(class '1) (int \0)}})
   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 Clojure