Created
June 21, 2013 11:27
-
-
Save ray1729/5830608 to your computer and use it in GitHub Desktop.
Using Clojure to compute partitions of a set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn expand-partition | |
"Given a partition of size n and an element, generate n new | |
partitions by adding `element` to each subset in turn." | |
[partition element] | |
(let [partition (vec partition)] | |
(for [i (range (count partition))] | |
(set (update-in partition [i] #(conj % element)))))) | |
(defn partitions | |
"Return all partitions of the set `X` into `n` non-empty subsets. | |
When `n` is not specified, return all partitions of `X`" | |
([X n] | |
(cond | |
(< n 1) '() | |
(> n (count X)) '() | |
(= n 1) (list #{X}) | |
(= n (count X)) (list (set (map hash-set X))) | |
:else (let [x (first X) | |
xs (disj X x)] | |
(lazy-cat (map (fn [p] (conj p #{x})) (partitions xs (dec n))) | |
(mapcat (fn [p] (expand-partition p x)) (partitions xs n)))))) | |
([X] | |
(mapcat (partial partitions X) (range 1 (inc (count X)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment