Created
April 13, 2014 01:56
-
-
Save agarman/10565555 to your computer and use it in GitHub Desktop.
Helpful combinatoric functions for Clojure
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 powerset [[h & t]] | |
(if (nil? h) | |
[()] | |
(for [x (powerset t) | |
y [x (cons h x)]] | |
y))) | |
(defn tails [[ _ & t :as xs]] | |
(when xs (cons xs (tails t)))) | |
(defn k-combinations [k l] | |
(if (zero? k) | |
[[]] | |
(for [[x & xs] (tails (seq l)) | |
ys (k-combinations (dec k) xs)] | |
(cons x ys)))) | |
(defn combinations [& [hs & tss]] | |
(if (empty? hs) | |
[[]] | |
(for [h hs | |
ts (apply combinations tss)] | |
(cons h ts)))) | |
(defn distribute [e [h & t :as xs]] | |
(if (empty? xs) | |
[[e]] | |
(cons (cons e xs) | |
(map #(cons h %) (distribute e t))))) | |
(defn permutations [xs] | |
(if-let [[e & t] xs] | |
(mapcat #(distribute e %) (permutations t)) | |
[[]])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment